Show some respect to pep8 and fellow readers.

This commit is contained in:
Alexis Métaireau 2017-06-28 21:31:31 +02:00
parent 603ac10d6e
commit 51b5bb46f7
8 changed files with 150 additions and 94 deletions

View file

@ -1,14 +1,31 @@
# You can find more information about what these settings mean in the
# documentation, available online at
# http://ihatemoney.readthedocs.io/en/latest/installation.html#configuration
# Turn this on if you want to have more output on what's happening under the
# hood.
DEBUG = False
# The database URI, reprensenting the type of database and how to connect to it.
# Enter an absolute path here.
SQLALCHEMY_DATABASE_URI = 'sqlite:///budget.db'
SQLACHEMY_ECHO = DEBUG
# Will likely become the default value in flask-sqlalchemy >=3 ; could be removed
# then:
SQLALCHEMY_TRACK_MODIFICATIONS = False
# You need to change this secret key, otherwise bad things might happen to your
# users.
SECRET_KEY = "tralala"
# A python tuple describing the name and email adress of the sender of the mails.
MAIL_DEFAULT_SENDER = ("Budget manager", "budget@notmyidea.org")
# If set to True, a demonstration project will be activated.
ACTIVATE_DEMO_PROJECT = True
# If not empty, the specified password must be entered to create new projects.
# DO NOT enter the password in cleartext. Generate a password hash with
# "ihatemoney generate_password_hash" instead.
ADMIN_PASSWORD = ""

View file

@ -12,6 +12,7 @@ from datetime import datetime
from jinja2 import Markup
from utils import slugify
def get_billform_for(project, set_default=True, **kwargs):
"""Return an instance of BillForm configured for a particular project.
@ -20,8 +21,9 @@ def get_billform_for(project, set_default=True, **kwargs):
"""
form = BillForm(**kwargs)
form.payed_for.choices = form.payer.choices = [(m.id, m.name)
for m in project.active_members]
active_members = [(m.id, m.name) for m in project.active_members]
form.payed_for.choices = form.payer.choices = active_members
form.payed_for.default = [m.id for m in project.active_members]
if set_default and request.method == "GET":
@ -30,7 +32,9 @@ def get_billform_for(project, set_default=True, **kwargs):
class CommaDecimalField(DecimalField):
"""A class to deal with comma in Decimal Field"""
def process_formdata(self, value):
if value:
value[0] = str(value[0]).replace(',', '.')
@ -69,12 +73,13 @@ class ProjectForm(EditProjectForm):
def validate_id(form, field):
form.id.data = slugify(field.data)
if (form.id.data == "dashboard") or Project.query.get(form.id.data):
raise ValidationError(Markup(_("The project identifier is used "
"to log in and for the URL of the project. "
"We tried to generate an identifier for you but a project "
"with this identifier already exists. "
"Please create a new identifier "
"that you will be able to remember.")))
message = _("The project identifier is used to log in and for the "
"URL of the project. "
"We tried to generate an identifier for you but a "
"project with this identifier already exists. "
"Please create a new identifier that you will be able "
"to remember")
raise ValidationError(Markup(message))
class AuthenticationForm(FlaskForm):
@ -178,13 +183,13 @@ class InviteForm(FlaskForm):
class ExportForm(FlaskForm):
export_type = SelectField(_("What do you want to download ?"),
export_type = SelectField(
_("What do you want to download ?"),
validators=[Required()],
coerce=str,
choices=[("bills", _("bills")), ("transactions", _("transactions"))]
)
export_format = SelectField(_("Export file format"),
choices=[("bills", _("bills")), ("transactions", _("transactions"))])
export_format = SelectField(
_("Export file format"),
validators=[Required()],
coerce=str,
choices=[("csv", "csv"), ("json", "json")]
)
choices=[("csv", "csv"), ("json", "json")])

View file

@ -10,7 +10,8 @@ from getpass import getpass
class GeneratePasswordHash(Command):
"Get password from user and hash it without printing it in clear text"
"""Get password from user and hash it without printing it in clear text."""
def run(self):
password = getpass(prompt='Password: ')

View file

@ -9,9 +9,6 @@ from sqlalchemy import orm
db = SQLAlchemy()
# define models
class Project(db.Model):
_to_serialize = ("id", "name", "password", "contact_email",
@ -37,7 +34,8 @@ class Project(db.Model):
# for each person
for person in self.members:
# get the list of bills he has to pay
bills = Bill.query.options(orm.subqueryload(Bill.owers)).filter(Bill.owers.contains(person))
bills = Bill.query.options(orm.subqueryload(Bill.owers)).filter(
Bill.owers.contains(person))
for bill in bills.all():
if person != bill.payer:
share = bill.pay_each() * person.weight
@ -56,6 +54,7 @@ class Project(db.Model):
def get_transactions_to_settle_bill(self, pretty_output=False):
"""Return a list of transactions that could be made to settle the bill"""
def prettify(transactions, pretty_output):
""" Return pretty transactions
"""
@ -63,9 +62,11 @@ class Project(db.Model):
return transactions
pretty_transactions = []
for transaction in transactions:
pretty_transactions.append({'ower': transaction['ower'].name,
pretty_transactions.append({
'ower': transaction['ower'].name,
'receiver': transaction['receiver'].name,
'amount': round(transaction['amount'], 2)})
'amount': round(transaction['amount'], 2)
})
return pretty_transactions
# cache value for better performance
@ -77,22 +78,36 @@ class Project(db.Model):
credits.append({"person": person, "balance": balance[person.id]})
elif round(balance[person.id], 2) < 0:
debts.append({"person": person, "balance": -balance[person.id]})
# Try and find exact matches
for credit in credits:
match = self.exactmatch(round(credit["balance"], 2), debts)
if match:
for m in match:
transactions.append({"ower": m["person"], "receiver": credit["person"], "amount": m["balance"]})
transactions.append({
"ower": m["person"],
"receiver": credit["person"],
"amount": m["balance"]
})
debts.remove(m)
credits.remove(credit)
# Split any remaining debts & credits
while credits and debts:
if credits[0]["balance"] > debts[0]["balance"]:
transactions.append({"ower": debts[0]["person"], "receiver": credits[0]["person"], "amount": debts[0]["balance"]})
transactions.append({
"ower": debts[0]["person"],
"receiver": credits[0]["person"],
"amount": debts[0]["balance"]
})
credits[0]["balance"] = credits[0]["balance"] - debts[0]["balance"]
del debts[0]
else:
transactions.append({"ower": debts[0]["person"], "receiver": credits[0]["person"], "amount": credits[0]["balance"]})
transactions.append({
"ower": debts[0]["person"],
"receiver": credits[0]["person"],
"amount": credits[0]["balance"]
})
debts[0]["balance"] = debts[0]["balance"] - credits[0]["balance"]
del credits[0]
@ -136,12 +151,15 @@ class Project(db.Model):
owers = [ower.name for ower in bill.owers]
else:
owers = ', '.join([ower.name for ower in bill.owers])
pretty_bills.append({"what": bill.what,
pretty_bills.append({
"what": bill.what,
"amount": round(bill.amount, 2),
"date": str(bill.date),
"payer_name": Person.query.get(bill.payer_id).name,
"payer_weight": Person.query.get(bill.payer_id).weight,
"owers": owers})
"owers": owers
})
return pretty_bills
def remove_member(self, member_id):
@ -176,6 +194,7 @@ class Project(db.Model):
class Person(db.Model):
class PersonQuery(BaseQuery):
def get_by_name(self, name, project):
return Person.query.filter(Person.name == name)\
.filter(Project.id == project.id).one()
@ -212,7 +231,8 @@ class Person(db.Model):
return "<Person %s for project %s>" % (self.name, self.project.name)
# We need to manually define a join table for m2m relations
billowers = db.Table('billowers',
billowers = db.Table(
'billowers',
db.Column('bill_id', db.Integer, db.ForeignKey('bill.id')),
db.Column('person_id', db.Integer, db.ForeignKey('person.id')),
)
@ -224,11 +244,11 @@ class Bill(db.Model):
def get(self, project, id):
try:
return self.join(Person, Project)\
.filter(Bill.payer_id == Person.id)\
.filter(Person.project_id == Project.id)\
.filter(Project.id == project.id)\
.filter(Bill.id == id).one()
return (self.join(Person, Project)
.filter(Bill.payer_id == Person.id)
.filter(Person.project_id == Project.id)
.filter(Project.id == project.id)
.filter(Bill.id == id).one())
except orm.exc.NoResultFound:
return None
@ -262,8 +282,10 @@ class Bill(db.Model):
return 0
def __repr__(self):
return "<Bill of %s from %s for %s>" % (self.amount,
self.payer, ", ".join([o.name for o in self.owers]))
return "<Bill of %s from %s for %s>" % (
self.amount,
self.payer, ", ".join([o.name for o in self.owers])
)
class Archive(db.Model):

View file

@ -106,6 +106,7 @@ babel = Babel(app)
# sentry
sentry = Sentry(app)
@babel.localeselector
def get_locale():
# get the lang from the session if defined, fallback on the browser "accept
@ -114,6 +115,7 @@ def get_locale():
setattr(g, 'lang', lang)
return lang
def main():
app.run(host="0.0.0.0", debug=True)

View file

@ -26,7 +26,9 @@ def slugify(value):
value = six.text_type(re.sub('[^\w\s-]', '', value).strip().lower())
return re.sub('[-\s]+', '-', value)
class Redirect303(HTTPException, RoutingException):
"""Raise if the map requests a redirect. This is for example the case if
`strict_slashes` are activated and an url that requires a trailing slash.
@ -43,6 +45,7 @@ class Redirect303(HTTPException, RoutingException):
class PrefixedWSGI(object):
'''
Wrap the application in this middleware and configure the
front-end server to add these headers, to let you quietly bind
@ -55,6 +58,7 @@ class PrefixedWSGI(object):
:param app: the WSGI application
'''
def __init__(self, app):
self.app = app
self.wsgi_app = app.wsgi_app
@ -85,12 +89,14 @@ def minimal_round(*args, **kw):
ires = int(res)
return (res if res != ires else ires)
def list_of_dicts2json(dict_to_convert):
"""Take a list of dictionnaries and turns it into
a json in-memory file
"""
return BytesIO(dumps(dict_to_convert).encode('utf-8'))
def list_of_dicts2csv(dict_to_convert):
"""Take a list of dictionnaries and turns it into
a csv in-memory file, assume all dict have the same keys
@ -110,7 +116,8 @@ def list_of_dicts2csv(dict_to_convert):
csv_data = []
csv_data.append([key.encode('utf-8') for key in dict_to_convert[0].keys()])
for dic in dict_to_convert:
csv_data.append([dic[h].encode('utf8')
csv_data.append(
[dic[h].encode('utf8')
if isinstance(dic[h], unicode) else str(dic[h]).encode('utf8')
for h in dict_to_convert[0].keys()])
except (KeyError, IndexError):

View file

@ -9,12 +9,13 @@ some shortcuts to make your life better when coding (see `pull_project`
and `add_project_id` for a quick overview)
"""
from flask import Blueprint, current_app, flash, g, redirect, \
render_template, request, session, url_for, send_file
from flask import (
Blueprint, current_app, flash, g, redirect, render_template, request,
session, url_for, send_file
)
from flask_mail import Mail, Message
from flask_babel import get_locale, gettext as _
from werkzeug.security import generate_password_hash, \
check_password_hash
from werkzeug.security import generate_password_hash, check_password_hash
from smtplib import SMTPRecipientsRefused
import werkzeug
from sqlalchemy import orm
@ -22,9 +23,11 @@ from functools import wraps
# local modules
from models import db, Project, Person, Bill
from forms import AdminAuthenticationForm, AuthenticationForm, EditProjectForm, \
InviteForm, MemberForm, PasswordReminder, ProjectForm, get_billform_for, \
from forms import (
AdminAuthenticationForm, AuthenticationForm, EditProjectForm,
InviteForm, MemberForm, PasswordReminder, ProjectForm, get_billform_for,
ExportForm
)
from utils import Redirect303, list_of_dicts2json, list_of_dicts2csv
main = Blueprint("main", __name__)

View file

@ -76,7 +76,8 @@ properly.
| Setting name | Default | What does it do? |
+============================+===========================+========================================================================================+
| SQLALCHEMY_DATABASE_URI | ``sqlite:///budget.db`` | Specifies the type of backend to use and its location. More information |
| | | on the format used can be found on `the SQLAlchemy documentation`. |
| | | on the format used can be found on `the SQLAlchemy documentation |
| | | <http://docs.sqlalchemy.org/en/latest/core/engines.html#database-urls>`_. |
+----------------------------+---------------------------+----------------------------------------------------------------------------------------+
| SECRET_KEY | ``tralala`` | The secret key used to encrypt the cookies. **This needs to be changed**. |
+----------------------------+---------------------------+----------------------------------------------------------------------------------------+
@ -90,8 +91,6 @@ properly.
| | | and copy its output into the value of *ADMIN_PASSWORD*. |
+----------------------------+---------------------------+----------------------------------------------------------------------------------------+
.. _`the SQLAlechemy documentation`: http://docs.sqlalchemy.org/en/latest/core/engines.html#database-urls
In a production environment
---------------------------