From d21f2d48f5fb9bf194e02c2d1cba5c77c65a9ae6 Mon Sep 17 00:00:00 2001 From: Jan-Pieter Baert Date: Mon, 9 Sep 2019 23:19:21 +0200 Subject: [PATCH 1/6] Fix pylint for database files --- app/database/add_admins.py | 2 ++ app/database/add_fitchen.py | 10 ++++++---- app/database/add_oceans_garden.py | 2 ++ app/database/add_primadonna.py | 4 ++++ app/database/add_simpizza.py | 5 ++++- app/database/add_stefanos.py | 8 +++++--- app/database/create_database.py | 24 ++++++++++++++---------- 7 files changed, 37 insertions(+), 18 deletions(-) diff --git a/app/database/add_admins.py b/app/database/add_admins.py index cb385c7..f47dfe0 100644 --- a/app/database/add_admins.py +++ b/app/database/add_admins.py @@ -1,8 +1,10 @@ +"Script for adding users as admin to Haldis." from app import db from models import User def add() -> None: + "Add users as admin." feli = User() feli.configure("feliciaan", True, 0) db.session.add(feli) diff --git a/app/database/add_fitchen.py b/app/database/add_fitchen.py index b9a885e..ff55132 100644 --- a/app/database/add_fitchen.py +++ b/app/database/add_fitchen.py @@ -1,3 +1,4 @@ +"Script to add Fitchen to Haldis" from app import db from models import Location, Product @@ -23,14 +24,15 @@ pricedict = {"Small": 799, "Medium": 999, "Large": 1199} def add() -> None: - simpizza = Location() - simpizza.configure("Fitchen", "?", "?", "https://www.fitchen.be/") - db.session.add(simpizza) + "Add Fitchen to the database" + fitchen = Location() + fitchen.configure("Fitchen", "?", "?", "https://www.fitchen.be/") + db.session.add(fitchen) for menuitem in menuitems: for size, price in pricedict.items(): for container in ["bowl", "wrap"]: name = "%s %s in %s" % (size, menuitem, container) entry = Product() - entry.configure(simpizza, name, price) + entry.configure(fitchen, name, price) db.session.add(entry) diff --git a/app/database/add_oceans_garden.py b/app/database/add_oceans_garden.py index fb293ef..a89fda8 100644 --- a/app/database/add_oceans_garden.py +++ b/app/database/add_oceans_garden.py @@ -1,3 +1,4 @@ +"Script to add Ocean Garden to Haldis" from itertools import product from app import db @@ -30,6 +31,7 @@ specials = [ def add() -> None: + "Add Ocean Garden to the database" chinees = Location() chinees.configure( "Oceans's Garden", diff --git a/app/database/add_primadonna.py b/app/database/add_primadonna.py index 5bbb3c4..b940652 100644 --- a/app/database/add_primadonna.py +++ b/app/database/add_primadonna.py @@ -1,8 +1,10 @@ +"Script to add Primadonna to Haldis" from app import db from models import Location, Product def add(): + "Add Primadonna to the database" addTA() addAfhalen() @@ -47,6 +49,7 @@ pizzasTA = { def addTA() -> None: + "Add Primadonna on takeaway.com to the database" primadonna_takeaway = Location() primadonna_takeaway.configure( "Primadonna (takeaway laten bezorgen)", @@ -102,6 +105,7 @@ pizzasAfhalen = { def addAfhalen() -> None: + "Add Primadonna to takeaway to the database" primadonna_afhalen = Location() primadonna_afhalen.configure( "Primadonna (bellen en afhalen)", diff --git a/app/database/add_simpizza.py b/app/database/add_simpizza.py index 77a6c0f..1a3e938 100644 --- a/app/database/add_simpizza.py +++ b/app/database/add_simpizza.py @@ -1,3 +1,4 @@ +"Script to add SimPizza to Haldis" from app import db from models import Location, Product @@ -19,7 +20,8 @@ pizzas = [ "Chicken bbq", "Funky chicken", "Veggie", - "Meat lovers" "Scampi mampi", + "Meat lovers", + "Scampi mampi", "Tabasco", "Chicken time", "Meatballs", @@ -33,6 +35,7 @@ pizzas = [ def add() -> None: + "Add Simpizza to the database" simpizza = Location() simpizza.configure( "Sim-pizza", diff --git a/app/database/add_stefanos.py b/app/database/add_stefanos.py index 9868d29..8cb0fc5 100644 --- a/app/database/add_stefanos.py +++ b/app/database/add_stefanos.py @@ -1,3 +1,4 @@ +"Script to add Stefanos to Haldis" from app import db from models import Location, Product @@ -101,12 +102,13 @@ data = [special_bickies, specials, vlezekes, friet] def add() -> None: + "Add Stefanos to the database" stefanos = Location() stefanos.configure( "Stefano's Place", "Overpoortstraat 12 9000 Gent", "tel: geen", - "https://www.facebook.com/pages/category/Fast-Food-Restaurant/Stefanos-Place-370774480004139/", + "https://www.facebook.com/pages/category/Fast-Food-Restaurant/Stefanos-Place-370774480004139/", # pylint: disable=C0301 ) db.session.add(stefanos) @@ -120,8 +122,8 @@ def add() -> None: bicky_cheese.configure(stefanos, name + " cheese", price + 30) db.session.add(bicky_cheese) - for dict in data: - for name, price in dict.items(): + for dictionary in data: + for name, price in dictionary.items(): item = Product() item.configure(stefanos, name, price) db.session.add(item) diff --git a/app/database/create_database.py b/app/database/create_database.py index 3af6957..128af81 100644 --- a/app/database/create_database.py +++ b/app/database/create_database.py @@ -1,3 +1,4 @@ +"Script for interaction and changes to the database" import add_admins import add_fitchen import add_oceans_garden @@ -17,27 +18,30 @@ yes = ["yes", "y", "Y"] no = ["no", "n", "N"] -# Commit all the things def commit() -> None: + "Commit all the things to the database" db.session.commit() print("Committing successful") def check_if_overwrite() -> bool: + "Check if the user wants to overwrite the previous database" answer = input("Do you want to overwrite the previous database? (y/N) ") return answer in yes def add_all() -> None: - for entry_set in entry_sets.keys(): + "Add all possible entries in the entry_sets to the database" + for entry_set, function in entry_sets.items(): print("Adding {}.".format(entry_set)) - entry_sets[entry_set]() + function() def recreate_from_scratch() -> None: - confirmation = "Are you very very sure? (Will delete previous entries!) (y/N) " + "Recreate a completely new database" + confirmation = "Are you very very sure? (Will delete previous entries!) (y/N) " # pylint: disable=C0301 check = "I acknowledge any repercussions!" - if input(confirmation) in yes and input("Type: '{}' ".format(check)) == check: + if input(confirmation) in yes and input("Type: '{}' ".format(check)) == check: # pylint: disable=C0301 print("Resetting the database!") db.drop_all() db.create_all() @@ -45,6 +49,7 @@ def recreate_from_scratch() -> None: def add_to_current() -> None: + "Add things to the current database" available = [entry_set for entry_set in entry_sets] def add_numbers() -> str: @@ -53,16 +58,14 @@ def add_to_current() -> None: ).rstrip(", ") while input("Do you still want to add something? (Y/n) ") not in no: - print( - "What do you want to add? (Use numbers, or A for all, or C for cancel) " - ) + print("What do you want to add? (Use numbers, or A for all, or C for cancel) ") # pylint: disable=C0301 answer = input("Available: {} : ".format(add_numbers())) if answer == "A": add_all() available = [] elif answer == "C": pass - elif answer.isnumeric() and answer in [str(x) for x in range(len(available))]: + elif answer.isnumeric() and answer in [str(x) for x in range(len(available))]: # pylint: disable=C0301 answer_index = int(answer) print("Adding {}.".format(available[answer_index])) entry_sets[str(available[answer_index])]() @@ -74,7 +77,8 @@ def add_to_current() -> None: manager = create_app() @manager.command -def setup_database(): +def setup_database(): #type: None + "Start the database interaction script" print("Database modification script!") print("=============================\n\n") if check_if_overwrite(): From ec82639c5c0d666e812cfc57930826e0902cdc03 Mon Sep 17 00:00:00 2001 From: Jan-Pieter Baert Date: Tue, 10 Sep 2019 01:06:11 +0200 Subject: [PATCH 2/6] Fix pylint for models files --- app/models/__init__.py | 2 ++ app/models/anonymous_user.py | 4 ++++ app/models/database.py | 1 + app/models/location.py | 8 +++++--- app/models/order.py | 20 ++++++++++++-------- app/models/orderitem.py | 7 +++++++ app/models/product.py | 14 ++++++++------ app/models/user.py | 4 ++++ 8 files changed, 43 insertions(+), 17 deletions(-) diff --git a/app/models/__init__.py b/app/models/__init__.py index 60576f2..4fcaf0a 100644 --- a/app/models/__init__.py +++ b/app/models/__init__.py @@ -1,3 +1,5 @@ +"The base file for everything related to the models" +# pylint: disable=C0301 # This file will expose what we want from the models module # This will probably be everything. But putting the imports here makes it possible to import all models in one line like this: # diff --git a/app/models/anonymous_user.py b/app/models/anonymous_user.py index 76f99f7..2ae10f2 100644 --- a/app/models/anonymous_user.py +++ b/app/models/anonymous_user.py @@ -1,3 +1,7 @@ +"AnonymouseUser for people who are not logged in the normal way" +# pylint: disable=R0201,C0111 + + class AnonymouseUser: id = None diff --git a/app/models/database.py b/app/models/database.py index f0b13d6..5f6799b 100644 --- a/app/models/database.py +++ b/app/models/database.py @@ -1,3 +1,4 @@ +# pylint: disable=C0111 from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() diff --git a/app/models/location.py b/app/models/location.py index 539e21d..15ad76c 100644 --- a/app/models/location.py +++ b/app/models/location.py @@ -1,9 +1,11 @@ +"Script for everything Location related in the database" import typing from models import db class Location(db.Model): + "Class used for configuring the Location model in the database" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(120), nullable=False) address = db.Column(db.String(254)) @@ -12,9 +14,9 @@ class Location(db.Model): products = db.relationship("Product", backref="location", lazy="dynamic") orders = db.relationship("Order", backref="location", lazy="dynamic") - def configure( - self, name: str, address: str, telephone: typing.Optional[str], website: str - ) -> None: + def configure(self, name: str, address: str, + telephone: typing.Optional[str], website: str) -> None: + "Configure the Location" self.name = name self.address = address self.website = website diff --git a/app/models/order.py b/app/models/order.py index 44718fd..1be6106 100644 --- a/app/models/order.py +++ b/app/models/order.py @@ -1,3 +1,4 @@ +"Script for everything Order related in the database" import typing from datetime import datetime @@ -7,6 +8,7 @@ from .user import User class Order(db.Model): + "Class used for configuring the Order model in the database" id = db.Column(db.Integer, primary_key=True) courrier_id = db.Column(db.Integer, nullable=True) location_id = db.Column(db.Integer, db.ForeignKey("location.id")) @@ -15,31 +17,31 @@ class Order(db.Model): public = db.Column(db.Boolean, default=True) items = db.relationship("OrderItem", backref="order", lazy="dynamic") - def configure( - self, - courrier: User, - location: Location, - starttime: db.DateTime, - stoptime: db.DateTime, - ) -> None: + def configure(self, courrier: User, location: Location, + starttime: db.DateTime, stoptime: db.DateTime,) -> None: + "Configure the Order" + # pylint: disable=W0201 self.courrier = courrier self.location = location self.starttime = starttime self.stoptime = stoptime def __repr__(self) -> str: + # pylint: disable=R1705 if self.location: return "Order %d @ %s" % (self.id, self.location.name or "None") else: return "Order %d" % (self.id) def group_by_user(self) -> typing.Dict[str, typing.Any]: + "Group items of an Order by user" group: typing.Dict[str, typing.Any] = dict() for item in self.items: user = group.get(item.get_name(), dict()) user["total"] = user.get("total", 0) + item.product.price user["to_pay"] = ( - user.get("to_pay", 0) + item.product.price if not item.paid else 0 + user.get("to_pay", 0) + + item.product.price if not item.paid else 0 ) user["paid"] = user.get("paid", True) and item.paid user["products"] = user.get("products", []) + [item.product] @@ -48,6 +50,7 @@ class Order(db.Model): return group def group_by_product(self) -> typing.Dict[str, typing.Any]: + "Group items of an Order by product" group: typing.Dict[str, typing.Any] = dict() for item in self.items: product = group.get(item.product.name, dict()) @@ -59,6 +62,7 @@ class Order(db.Model): return group def can_close(self, user_id: int) -> bool: + "Check if a user can close the Order" if self.stoptime and self.stoptime < datetime.now(): return False user = None diff --git a/app/models/orderitem.py b/app/models/orderitem.py index d699a90..8460a98 100644 --- a/app/models/orderitem.py +++ b/app/models/orderitem.py @@ -1,3 +1,4 @@ +"Script for everything OrderItem related in the database" from datetime import datetime from .database import db @@ -7,6 +8,7 @@ from .user import User class OrderItem(db.Model): + "Class used for configuring the OrderItem model in the database" id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey("user.id")) order_id = db.Column(db.Integer, db.ForeignKey("order.id"), nullable=False) @@ -20,11 +22,14 @@ class OrderItem(db.Model): name = db.Column(db.String(120)) def configure(self, user: User, order: Order, product: Product) -> None: + "Configure the OrderItem" + # pylint: disable=W0201 self.user = user self.order = order self.product = product def get_name(self) -> str: + "Get the name of the user which 'owns' the item" if self.user_id is not None and self.user_id > 0: return self.user.username return self.name @@ -39,7 +44,9 @@ class OrderItem(db.Model): product_name or "None", ) + # pylint: disable=W0613 def can_delete(self, order_id: int, user_id: int, name: str) -> bool: + "Check if a user can delete an item" if int(self.order_id) != int(order_id): return False if self.order.stoptime and self.order.stoptime < datetime.now(): diff --git a/app/models/product.py b/app/models/product.py index 7e8e1a7..d02c469 100644 --- a/app/models/product.py +++ b/app/models/product.py @@ -1,23 +1,25 @@ +"Script for everything Product related in the database" from models import db from .location import Location class Product(db.Model): + "Class used for configuring the Product model in the database" id = db.Column(db.Integer, primary_key=True) location_id = db.Column(db.Integer, db.ForeignKey("location.id")) name = db.Column(db.String(120), nullable=False) price = db.Column(db.Integer, nullable=False) - orderItems = db.relationship("OrderItem", backref="product", lazy="dynamic") + orderItems = db.relationship("OrderItem", + backref="product", lazy="dynamic") def configure(self, location: Location, name: str, price: int) -> None: + "Configure the Product" + # pylint: disable=W0201 self.location = location self.name = name self.price = price def __repr__(self) -> str: - return "%s (€%d)from %s" % ( - self.name, - self.price / 100, - self.location or "None", - ) + return "%s (€%d)from %s" % (self.name, self.price / 100, + self.location or "None",) diff --git a/app/models/user.py b/app/models/user.py index 4ed2fe8..463075e 100644 --- a/app/models/user.py +++ b/app/models/user.py @@ -1,7 +1,9 @@ +"Script for everything User related in the database" from models import db class User(db.Model): + "Class used for configuring the User model in the database" id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) admin = db.Column(db.Boolean) @@ -15,10 +17,12 @@ class User(db.Model): orderItems = db.relationship("OrderItem", backref="user", lazy="dynamic") def configure(self, username: str, admin: bool, bias: int) -> None: + "Configure the User" self.username = username self.admin = admin self.bias = bias + # pylint: disable=C0111, R0201 def is_authenticated(self) -> bool: return True From c4f9222558bb0af1d8d726ee61960d4da1a31b78 Mon Sep 17 00:00:00 2001 From: Jan-Pieter Baert Date: Tue, 10 Sep 2019 02:50:22 +0200 Subject: [PATCH 3/6] Fix pylint for views and templates --- app/notification.py | 4 +- app/templates/layout.html | 2 +- app/templates/locations.html | 2 +- app/templates/maps.html | 2 +- app/templates/order.html | 10 +-- app/templates/order_edit.html | 2 +- app/templates/utils.html | 2 +- app/views/debug.py | 2 + app/views/general.py | 22 ++++-- app/views/order.py | 127 ++++++++++++++++++++-------------- app/views/stats.py | 2 + 11 files changed, 106 insertions(+), 71 deletions(-) diff --git a/app/notification.py b/app/notification.py index db13610..622f920 100644 --- a/app/notification.py +++ b/app/notification.py @@ -11,7 +11,7 @@ def post_order_to_webhook(order_item) -> None: message = "" if order_item.courrier is not None: message = " {3} is going to {1}, order <{0}|here>! Deadline in {2} minutes!".format( - url_for("order_bp.order", id=order_item.id, _external=True), + url_for("order_bp.order_from_id", order_id=order_item.id, _external=True), order_item.location.name, remaining_minutes(order_item.stoptime), order_item.courrier.username.title(), @@ -20,7 +20,7 @@ def post_order_to_webhook(order_item) -> None: message = " New order for {}. Deadline in {} minutes. <{}|Open here.>".format( order_item.location.name, remaining_minutes(order_item.stoptime), - url_for("order_bp.order", id=order_item.id, _external=True), + url_for("order_bp.order_from_id", order_id=order_item.id, _external=True), ) webhookthread = WebhookSenderThread(message, app.config["SLACK_WEBHOOK"]) webhookthread.start() diff --git a/app/templates/layout.html b/app/templates/layout.html index e2af745..0072652 100644 --- a/app/templates/layout.html +++ b/app/templates/layout.html @@ -5,7 +5,7 @@ ('general_bp.home', 'Home'), ('order_bp.orders', 'Orders'), ('general_bp.locations', 'Locations'), - ('general_bp.map', 'Map'), + ('general_bp.map_view', 'Map'), ('general_bp.about', 'About'), ('stats_blueprint.stats', 'Stats'), ] -%} diff --git a/app/templates/locations.html b/app/templates/locations.html index b174404..c8b3b99 100644 --- a/app/templates/locations.html +++ b/app/templates/locations.html @@ -14,7 +14,7 @@ {% for loc in locations -%} - {{ loc.name }} + {{ loc.name }} {{ loc.address }} diff --git a/app/templates/maps.html b/app/templates/maps.html index 1aced1d..508a2e2 100644 --- a/app/templates/maps.html +++ b/app/templates/maps.html @@ -28,7 +28,7 @@ loc = { "address": "{{loc.address}}", "name": "{{loc.name}}", - "url": "{{ url_for('general_bp.location', id=loc.id) }}" + "url": "{{ url_for('general_bp.location', location_id=loc.id) }}" }; locations.push(loc); diff --git a/app/templates/order.html b/app/templates/order.html index 4096df4..50edf6b 100644 --- a/app/templates/order.html +++ b/app/templates/order.html @@ -11,16 +11,16 @@

Order {{ order.id }}
{% if order.can_close(current_user.id) -%} -
+
{% endif %}{% if courier_or_admin %} - Edit + Edit {%- endif %}

courier: {{ order.courrier.username }} {% if order.courrier == None and not current_user.is_anonymous() %} -
+
{% endif %} @@ -38,7 +38,7 @@ {% if form -%}

Order:

-
+ Choose for me @@ -99,7 +99,7 @@

Ordered products: {{ order.items.count() }}

- + {% for key, value in order.group_by_product().items() -%}
{{ key }}: {{ value["count"] }} diff --git a/app/templates/order_edit.html b/app/templates/order_edit.html index db8c6ac..b70faf9 100644 --- a/app/templates/order_edit.html +++ b/app/templates/order_edit.html @@ -11,7 +11,7 @@

Edit order:

- + {{ form.csrf_token }}
{{ form.courrier_id.label(class='control-label') }}
diff --git a/app/templates/utils.html b/app/templates/utils.html index 6e116ff..4abfa7c 100644 --- a/app/templates/utils.html +++ b/app/templates/utils.html @@ -9,7 +9,7 @@ Orders: {{ order.items.count() }}

{%- endmacro %} diff --git a/app/views/debug.py b/app/views/debug.py index 96177e7..aed320d 100644 --- a/app/views/debug.py +++ b/app/views/debug.py @@ -1,3 +1,4 @@ +"View used for debugging Haldis" from flask import Blueprint from flask import current_app as app from flask import url_for @@ -9,6 +10,7 @@ debug_bp = Blueprint("debug_bp", __name__) @debug_bp.route("/routes") @login_required def list_routes() -> str: + "List all routes of the application" import urllib output = [] diff --git a/app/views/general.py b/app/views/general.py index 9617ec9..d8423b4 100644 --- a/app/views/general.py +++ b/app/views/general.py @@ -1,3 +1,4 @@ +"Script to generate the general views of Haldis" import os from datetime import datetime, timedelta @@ -15,6 +16,7 @@ general_bp = Blueprint("general_bp", __name__) @general_bp.route("/") def home() -> str: + "Generate the home view" prev_day = datetime.now() - timedelta(days=1) recently_closed = get_orders( ((Order.stoptime > prev_day) & (Order.stoptime < datetime.now())) @@ -24,22 +26,24 @@ def home() -> str: ) -@general_bp.route("/map", defaults={"id": None}) -@general_bp.route("/map/") -def map(id) -> str: +@general_bp.route("/map") +def map_view() -> str: + "Generate the map view" locs = Location.query.order_by("name") return render_template("maps.html", locations=locs) @general_bp.route("/location") def locations() -> str: + "Generate the location view" locs = Location.query.order_by("name") return render_template("locations.html", locations=locs) -@general_bp.route("/location/") -def location(id) -> str: - loc = Location.query.filter(Location.id == id).first() +@general_bp.route("/location/") +def location(location_id) -> str: + "Generate the location view given an id" + loc = Location.query.filter(Location.id == location_id).first() if loc is None: abort(404) return render_template("location.html", location=loc, title=loc.name) @@ -47,18 +51,22 @@ def location(id) -> str: @general_bp.route("/about/") def about() -> str: + "Generate the about view" return render_template("about.html") @general_bp.route("/profile/") @login_required def profile() -> str: + "Generate the profile view" return render_template("profile.html") @general_bp.route("/favicon.ico") def favicon() -> str: - if len(get_orders((Order.stoptime > datetime.now()))) == 0: + "Generate the favicon" + # pylint: disable=R1705 + if not get_orders((Order.stoptime > datetime.now())): return send_from_directory( os.path.join(str(app.root_path), "static"), "favicon.ico", diff --git a/app/views/order.py b/app/views/order.py index b9d4b16..ad0cae9 100644 --- a/app/views/order.py +++ b/app/views/order.py @@ -1,13 +1,13 @@ +"Script to generate the order related views of Haldis" import random import typing from datetime import datetime -import werkzeug +from werkzeug.wrappers import Response # from flask import current_app as app from flask import (Blueprint, abort, flash, redirect, render_template, request, session, url_for, wrappers) from flask_login import current_user, login_required -from werkzeug.wrappers import Response from forms import AnonOrderItemForm, OrderForm, OrderItemForm from models import Order, OrderItem, User, db @@ -18,6 +18,7 @@ order_bp = Blueprint("order_bp", "order") @order_bp.route("/") def orders(form: OrderForm = None) -> str: + "Generate general order view" if form is None and not current_user.is_anonymous(): form = OrderForm() location_id = request.args.get("location_id") @@ -30,6 +31,7 @@ def orders(form: OrderForm = None) -> str: @order_bp.route("/create", methods=["POST"]) @login_required def order_create() -> typing.Union[str, Response]: + "Generate order create view" orderForm = OrderForm() orderForm.populate() if orderForm.validate_on_submit(): @@ -38,33 +40,35 @@ def order_create() -> typing.Union[str, Response]: db.session.add(order) db.session.commit() post_order_to_webhook(order) - return redirect(url_for("order_bp.order", id=order.id)) + return redirect(url_for("order_bp.order_from_id", order_id=order.id)) return orders(form=orderForm) -@order_bp.route("/") -def order(id: int, form: OrderForm = None) -> str: - order = Order.query.filter(Order.id == id).first() +@order_bp.route("/") +def order_from_id(order_id: int, form: OrderForm = None) -> str: + "Generate order view from id" + order = Order.query.filter(Order.id == order_id).first() if order is None: abort(404) if current_user.is_anonymous() and not order.public: flash("Please login to see this order.", "info") abort(401) if form is None: - form = AnonOrderItemForm() if current_user.is_anonymous() else OrderItemForm() + form = AnonOrderItemForm() if current_user.is_anonymous() \ + else OrderItemForm() form.populate(order.location) if order.stoptime and order.stoptime < datetime.now(): form = None total_price = sum([o.product.price for o in order.items]) debts = sum([o.product.price for o in order.items if not o.paid]) - return render_template( - "order.html", order=order, form=form, total_price=total_price, debts=debts - ) + return render_template("order.html", order=order, form=form, + total_price=total_price, debts=debts) -@order_bp.route("//items") -def items_showcase(id: int, form: OrderForm = None) -> str: - order = Order.query.filter(Order.id == id).first() +@order_bp.route("//items") +def items_showcase(order_id: int) -> str: + "Generate order items view from id" + order = Order.query.filter(Order.id == order_id).first() if order is None: abort(404) if current_user.is_anonymous() and not order.public: @@ -73,11 +77,13 @@ def items_showcase(id: int, form: OrderForm = None) -> str: return render_template("order_items.html", order=order) -@order_bp.route("//edit", methods=["GET", "POST"]) +@order_bp.route("//edit", methods=["GET", "POST"]) @login_required -def order_edit(id: int) -> typing.Union[str, Response]: - order = Order.query.filter(Order.id == id).first() - if current_user.id is not order.courrier_id and not current_user.is_admin(): +def order_edit(order_id: int) -> typing.Union[str, Response]: + "Generate order edit view from id" + order = Order.query.filter(Order.id == order_id).first() + if current_user.id is not order.courrier_id and \ + not current_user.is_admin(): abort(401) if order is None: abort(404) @@ -86,15 +92,17 @@ def order_edit(id: int) -> typing.Union[str, Response]: if orderForm.validate_on_submit(): orderForm.populate_obj(order) db.session.commit() - return redirect(url_for("order_bp.order", id=order.id)) - return render_template("order_edit.html", form=orderForm, order_id=id) + return redirect(url_for("order_bp.order_from_id", order_id=order.id)) + return render_template("order_edit.html", form=orderForm, + order_id=order_id) -@order_bp.route("//create", methods=["POST"]) -def order_item_create(id: int) -> typing.Any: +@order_bp.route("//create", methods=["POST"]) +def order_item_create(order_id: int) -> typing.Any: # type is 'typing.Union[str, Response]', but this errors due to # https://github.com/python/mypy/issues/7187 - current_order = Order.query.filter(Order.id == id).first() + "Add item to order from id" + current_order = Order.query.filter(Order.id == order_id).first() if current_order is None: abort(404) if current_order.stoptime and current_order.stoptime < datetime.now(): @@ -102,12 +110,13 @@ def order_item_create(id: int) -> typing.Any: if current_user.is_anonymous() and not current_order.public: flash("Please login to see this order.", "info") abort(401) - form = AnonOrderItemForm() if current_user.is_anonymous() else OrderItemForm() + form = AnonOrderItemForm() if current_user.is_anonymous() \ + else OrderItemForm() form.populate(current_order.location) if form.validate_on_submit(): item = OrderItem() form.populate_obj(item) - item.order_id = id + item.order_id = order_id if not current_user.is_anonymous(): item.user_id = current_user.id else: @@ -115,26 +124,31 @@ def order_item_create(id: int) -> typing.Any: db.session.add(item) db.session.commit() flash("Ordered %s" % (item.product.name), "success") - return redirect(url_for("order_bp.order", id=id)) - return order(id, form=form) + return redirect(url_for("order_bp.order_from_id", order_id=order_id)) + return order_from_id(order_id, form=form) @order_bp.route("///paid", methods=["POST"]) @login_required +# pylint: disable=R1710 def item_paid(order_id: int, item_id: int) -> typing.Optional[Response]: + "Indicate payment status for an item in an order" item = OrderItem.query.filter(OrderItem.id == item_id).first() - id = current_user.id - if item.order.courrier_id == id or current_user.admin: + user_id = current_user.id + if item.order.courrier_id == user_id or current_user.admin: item.paid = True db.session.commit() - flash("Paid %s by %s" % (item.product.name, item.get_name()), "success") - return redirect(url_for("order_bp.order", id=order_id)) + flash("Paid %s by %s" % (item.product.name, item.get_name()), + "success") + return redirect(url_for("order_bp.order_from_id", order_id=order_id)) abort(404) @order_bp.route("///user_paid", methods=["POST"]) @login_required -def items_user_paid(order_id: int, user_name: str) -> typing.Optional[Response]: +# pylint: disable=R1710 +def items_user_paid(order_id: int, user_name: str) -> typing.Optional[Response]: # pylint:disable=C0301 + "Indicate payment status for a user in an order" user = User.query.filter(User.username == user_name).first() items: typing.List[OrderItem] = [] if user: @@ -152,33 +166,37 @@ def items_user_paid(order_id: int, user_name: str) -> typing.Optional[Response]: for item in items: item.paid = True db.session.commit() - flash("Paid %d items for %s" % (len(items), item.get_name()), "success") - return redirect(url_for("order_bp.order", id=order_id)) + flash("Paid %d items for %s" % + (len(items), item.get_name()), "success") + return redirect(url_for("order_bp.order_from_id", order_id=order_id)) abort(404) @order_bp.route("///delete", methods=["POST"]) +# pylint: disable=R1710 def delete_item(order_id: int, item_id: int) -> typing.Any: # type is 'typing.Optional[Response]', but this errors due to # https://github.com/python/mypy/issues/7187 + "Delete an item from an order" item = OrderItem.query.filter(OrderItem.id == item_id).first() - id = None + user_id = None if not current_user.is_anonymous(): print("%s tries to delete orders" % (current_user.username)) - id = current_user.id - if item.can_delete(order_id, id, session.get("anon_name", "")): + user_id = current_user.id + if item.can_delete(order_id, user_id, session.get("anon_name", "")): product_name = item.product.name db.session.delete(item) db.session.commit() flash("Deleted %s" % (product_name), "success") - return redirect(url_for("order_bp.order", id=order_id)) + return redirect(url_for("order_bp.order_from_id", order_id=order_id)) abort(404) -@order_bp.route("//volunteer", methods=["POST"]) +@order_bp.route("//volunteer", methods=["POST"]) @login_required -def volunteer(id: int) -> Response: - order = Order.query.filter(Order.id == id).first() +def volunteer(order_id: int) -> Response: + "Add a volunteer to an order" + order = Order.query.filter(Order.id == order_id).first() if order is None: abort(404) if order.courrier_id is None or order.courrier_id == 0: @@ -187,18 +205,18 @@ def volunteer(id: int) -> Response: flash("Thank you for volunteering!") else: flash("Volunteering not possible!") - return redirect(url_for("order_bp.order", id=id)) + return redirect(url_for("order_bp.order_from_id", order_id=order_id)) -@order_bp.route("//close", methods=["POST"]) +@order_bp.route("//close", methods=["POST"]) @login_required -def close_order(id: int) -> typing.Optional[Response]: - order = Order.query.filter(Order.id == id).first() +def close_order(order_id: int) -> typing.Optional[Response]: + "Close an order" + order = Order.query.filter(Order.id == order_id).first() if order is None: abort(404) if (current_user.id == order.courrier_id or current_user.is_admin()) and ( - order.stoptime is None or (order.stoptime > datetime.now()) - ): + order.stoptime is None or (order.stoptime > datetime.now())): order.stoptime = datetime.now() if order.courrier_id == 0 or order.courrier_id is None: courrier = select_user(order.items) @@ -206,7 +224,7 @@ def close_order(id: int) -> typing.Optional[Response]: if courrier is not None: order.courrier_id = courrier.id db.session.commit() - return redirect(url_for("order_bp.order", id=id)) + return redirect(url_for("order_bp.order_from_id", order_id=order_id)) # The line below is to make sure mypy doesn't say # "Missing return statement" # https://github.com/python/mypy/issues/4223 @@ -214,11 +232,12 @@ def close_order(id: int) -> typing.Optional[Response]: def select_user(items) -> typing.Optional[User]: + "Select a random user from those who are signed up for the order" user = None # remove non users items = [i for i in items if i.user_id] - if len(items) <= 0: + if not items: return None while user is None: @@ -232,13 +251,17 @@ def select_user(items) -> typing.Optional[User]: def get_orders(expression=None) -> typing.List[Order]: - orders: typing.List[OrderForm] = [] + "Give the list of all currently open and public Orders" + order_list: typing.List[OrderForm] = [] if expression is None: expression = (datetime.now() > Order.starttime) & ( Order.stoptime > datetime.now() + # pylint: disable=C0121 ) | (Order.stoptime == None) if not current_user.is_anonymous(): - orders = Order.query.filter(expression).all() + order_list = Order.query.filter(expression).all() else: - orders = Order.query.filter((expression & (Order.public == True))).all() - return orders + order_list = Order.query.filter( + # pylint: disable=C0121 + (expression & (Order.public == True))).all() + return order_list diff --git a/app/views/stats.py b/app/views/stats.py index 73ad1b1..02771a2 100644 --- a/app/views/stats.py +++ b/app/views/stats.py @@ -1,3 +1,4 @@ +"Script to generate the stats related views of Haldis" from flask import Blueprint from flask import current_app as app from flask import render_template @@ -9,6 +10,7 @@ stats_blueprint = Blueprint("stats_blueprint", __name__) @stats_blueprint.route("/") def stats() -> str: + "Generate Haldis data in a pretty format" data = { "amount": { "orders": FatOrder.amount(), From 48641adf90e78c79ac1084c383c5122ffdaaf902 Mon Sep 17 00:00:00 2001 From: Jan-Pieter Baert Date: Tue, 10 Sep 2019 15:17:35 +0200 Subject: [PATCH 4/6] Fix pylint for Haldis --- .pylintrc | 492 ++++++++++++++++++++++++++++++++++++++++++ app/admin.py | 25 ++- app/app.py | 45 ++-- app/config.example.py | 5 +- app/fatmodels.py | 9 +- app/forms.py | 19 +- app/login.py | 7 + app/migrations/env.py | 1 + app/notification.py | 15 +- app/passenger_wsgi.py | 1 + app/utils.py | 3 + app/zeus.py | 12 +- 12 files changed, 601 insertions(+), 33 deletions(-) create mode 100644 .pylintrc diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 0000000..cf85192 --- /dev/null +++ b/.pylintrc @@ -0,0 +1,492 @@ +[MASTER] + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. +extension-pkg-whitelist= + +# Add files or directories to the blacklist. They should be base names, not +# paths. +ignore=CVS + +# Add files or directories matching the regex patterns to the blacklist. The +# regex matches against base names, not paths. +ignore-patterns=.*.db + +# Python code to execute, usually for sys.path manipulation such as +# pygtk.require(). +#init-hook= + +# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the +# number of processors available to use. +jobs=0 + +# Control the amount of potential inferred values when inferring a single +# object. This can help the performance when dealing with large functions or +# complex, nested conditions. +limit-inference-results=100 + +# List of plugins (as comma separated values of python modules names) to load, +# usually to register additional checkers. +load-plugins= + +# Pickle collected data for later comparisons. +persistent=yes + +# Specify a configuration file. +#rcfile= + +# When enabled, pylint would attempt to guess common misconfiguration and emit +# user-friendly hints instead of false-positive error messages. +suggestion-mode=yes + +# Allow loading of arbitrary C extensions. Extensions are imported into the +# active Python interpreter and may run arbitrary code. +unsafe-load-any-extension=no + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED. +confidence= + +# Disable the message, report, category or checker with the given id(s). You +# can either give multiple identifiers separated by comma (,) or put this +# option multiple times (only on the command line, not in the configuration +# file where it should appear only once). You can also use "--disable=all" to +# disable everything first and then reenable specific checks. For example, if +# you want to run only the similarities checker, you can use "--disable=all +# --enable=similarities". If you want to run only the classes checker, but have +# no Warning level messages displayed, use "--disable=all --enable=classes +# --disable=W". +disable=E0401,E0611,C0103,W0511,W0611 + +# Enable the message, report, category or checker with the given id(s). You can +# either give multiple identifier separated by comma (,) or put this option +# multiple time (only on the command line, not in the configuration file where +# it should appear only once). See also the "--disable" option for examples. +enable=c-extension-no-member + + +[REPORTS] + +# Python expression which should return a note less than 10 (10 is the highest +# note). You have access to the variables errors warning, statement which +# respectively contain the number of errors / warnings messages and the total +# number of statements analyzed. This is used by the global evaluation report +# (RP0004). +evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) + +# Template used to display messages. This is a python new-style format string +# used to format the message information. See doc for all details. +#msg-template= + +# Set the output format. Available formats are text, parseable, colorized, json +# and msvs (visual studio). You can also give a reporter class, e.g. +# mypackage.mymodule.MyReporterClass. +output-format=text + +# Tells whether to display a full report or only the messages. +reports=no + +# Activate the evaluation score. +score=yes + + +[REFACTORING] + +# Maximum number of nested blocks for function / method body +max-nested-blocks=5 + +# Complete name of functions that never returns. When checking for +# inconsistent-return-statements if a never returning function is called then +# it will be considered as an explicit return statement and no message will be +# printed. +never-returning-functions=sys.exit + + +[SIMILARITIES] + +# Ignore comments when computing similarities. +ignore-comments=yes + +# Ignore docstrings when computing similarities. +ignore-docstrings=yes + +# Ignore imports when computing similarities. +ignore-imports=no + +# Minimum lines number of a similarity. +min-similarity-lines=4 + + +[TYPECHECK] + +# List of decorators that produce context managers, such as +# contextlib.contextmanager. Add to this list to register other decorators that +# produce valid context managers. +contextmanager-decorators=contextlib.contextmanager + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E1101 when accessed. Python regular +# expressions are accepted. +generated-members= + +# Tells whether missing members accessed in mixin class should be ignored. A +# mixin class is detected if its name ends with "mixin" (case insensitive). +ignore-mixin-members=yes + +# Tells whether to warn about missing members when the owner of the attribute +# is inferred to be None. +ignore-none=yes + +# This flag controls whether pylint should warn about no-member and similar +# checks whenever an opaque object is returned when inferring. The inference +# can return multiple potential results while evaluating a Python object, but +# some branches might not be evaluated, which results in partial inference. In +# that case, it might be useful to still emit no-member and other checks for +# the rest of the inferred objects. +ignore-on-opaque-inference=yes + +# List of class names for which member attributes should not be checked (useful +# for classes with dynamically set attributes). This supports the use of +# qualified names. +ignored-classes=optparse.Values,thread._local,_thread._local + +# List of module names for which member attributes should not be checked +# (useful for modules/projects where namespaces are manipulated during runtime +# and thus existing member attributes cannot be deduced by static analysis. It +# supports qualified module names, as well as Unix pattern matching. +ignored-modules= + +# Show a hint with possible names when a member name was not found. The aspect +# of finding the hint is based on edit distance. +missing-member-hint=yes + +# The minimum edit distance a name should have in order to be considered a +# similar match for a missing member name. +missing-member-hint-distance=1 + +# The total number of similar names that should be taken in consideration when +# showing a hint for a missing member. +missing-member-max-choices=1 + + +[LOGGING] + +# Format style used to check logging format string. `old` means using % +# formatting, while `new` is for `{}` formatting. +logging-format-style=old + +# Logging modules to check that the string format arguments are in logging +# function parameter format. +logging-modules=logging + + +[VARIABLES] + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid defining new builtins when possible. +additional-builtins= + +# Tells whether unused global variables should be treated as a violation. +allow-global-unused-variables=yes + +# List of strings which can identify a callback function by name. A callback +# name must start or end with one of those strings. +callbacks=cb_, + _cb + +# A regular expression matching the name of dummy variables (i.e. expected to +# not be used). +dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ + +# Argument names that match this expression will be ignored. Default to name +# with leading underscore. +ignored-argument-names=_.*|^ignored_|^unused_ + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# List of qualified module names which can have objects that can redefine +# builtins. +redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io + + +[SPELLING] + +# Limits count of emitted suggestions for spelling mistakes. +max-spelling-suggestions=4 + +# Spelling dictionary name. Available dictionaries: none. To make it working +# install python-enchant package.. +spelling-dict= + +# List of comma separated words that should not be checked. +spelling-ignore-words= + +# A path to a file that contains private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to indicated private dictionary in +# --spelling-private-dict-file option instead of raising a message. +spelling-store-unknown-words=no + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME, + XXX, + TODO + + +[BASIC] + +# Naming style matching correct argument names. +argument-naming-style=snake_case + +# Regular expression matching correct argument names. Overrides argument- +# naming-style. +#argument-rgx= + +# Naming style matching correct attribute names. +attr-naming-style=snake_case + +# Regular expression matching correct attribute names. Overrides attr-naming- +# style. +#attr-rgx= + +# Bad variable names which should always be refused, separated by a comma. +bad-names=foo, + bar, + baz, + toto, + tutu, + tata + +# Naming style matching correct class attribute names. +class-attribute-naming-style=any + +# Regular expression matching correct class attribute names. Overrides class- +# attribute-naming-style. +#class-attribute-rgx= + +# Naming style matching correct class names. +class-naming-style=PascalCase + +# Regular expression matching correct class names. Overrides class-naming- +# style. +#class-rgx= + +# Naming style matching correct constant names. +const-naming-style=UPPER_CASE + +# Regular expression matching correct constant names. Overrides const-naming- +# style. +#const-rgx= + +# Minimum line length for functions/classes that require docstrings, shorter +# ones are exempt. +docstring-min-length=-1 + +# Naming style matching correct function names. +function-naming-style=snake_case + +# Regular expression matching correct function names. Overrides function- +# naming-style. +#function-rgx= + +# Good variable names which should always be accepted, separated by a comma. +good-names=i, + j, + k, + ex, + Run, + _ + +# Include a hint for the correct naming format with invalid-name. +include-naming-hint=no + +# Naming style matching correct inline iteration names. +inlinevar-naming-style=any + +# Regular expression matching correct inline iteration names. Overrides +# inlinevar-naming-style. +#inlinevar-rgx= + +# Naming style matching correct method names. +method-naming-style=snake_case + +# Regular expression matching correct method names. Overrides method-naming- +# style. +#method-rgx= + +# Naming style matching correct module names. +module-naming-style=snake_case + +# Regular expression matching correct module names. Overrides module-naming- +# style. +#module-rgx= + +# Colon-delimited sets of names that determine each other's naming style when +# the name regexes allow several styles. +name-group= + +# Regular expression which should only match function or class names that do +# not require a docstring. +no-docstring-rgx=^_ + +# List of decorators that produce properties, such as abc.abstractproperty. Add +# to this list to register other decorators that produce valid properties. +# These decorators are taken in consideration only for invalid-name. +property-classes=abc.abstractproperty + +# Naming style matching correct variable names. +variable-naming-style=snake_case + +# Regular expression matching correct variable names. Overrides variable- +# naming-style. +#variable-rgx= + + +[STRING] + +# This flag controls whether the implicit-str-concat-in-sequence should +# generate a warning on implicit string concatenation in sequences defined over +# several lines. +check-str-concat-over-line-jumps=no + + +[FORMAT] + +# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. +expected-line-ending-format=LF + +# Regexp for a line that is allowed to be longer than the limit. +ignore-long-lines=^\s*(# )??$ + +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren=4 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' + +# Maximum number of characters on a single line. +max-line-length=80 + +# Maximum number of lines in a module. +max-module-lines=1000 + +# List of optional constructs for which whitespace checking is disabled. `dict- +# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. +# `trailing-comma` allows a space between comma and closing bracket: (a, ). +# `empty-line` allows space-only lines. +no-space-check=trailing-comma, + dict-separator + +# Allow the body of a class to be on the same line as the declaration if body +# contains single statement. +single-line-class-stmt=no + +# Allow the body of an if to be on the same line as the test if there is no +# else. +single-line-if-stmt=no + + +[DESIGN] + +# Maximum number of arguments for function / method. +max-args=5 + +# Maximum number of attributes for a class (see R0902). +max-attributes=7 + +# Maximum number of boolean expressions in an if statement. +max-bool-expr=5 + +# Maximum number of branch for function / method body. +max-branches=12 + +# Maximum number of locals for function / method body. +max-locals=15 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=20 + +# Maximum number of return / yield for function / method body. +max-returns=6 + +# Maximum number of statements in function / method body. +max-statements=50 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=2 + + +[CLASSES] + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__, + __new__, + setUp + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict, + _fields, + _replace, + _source, + _make + +# List of valid names for the first argument in a class method. +valid-classmethod-first-arg=cls + +# List of valid names for the first argument in a metaclass class method. +valid-metaclass-classmethod-first-arg=cls + + +[IMPORTS] + +# Allow wildcard imports from modules that define __all__. +allow-wildcard-with-all=no + +# Analyse import fallback blocks. This can be used to support both Python 2 and +# 3 compatible code, which means that the block might have code that exists +# only in one or another interpreter, leading to false positives when analysed. +analyse-fallback-blocks=no + +# Deprecated modules which should not be used, separated by a comma. +deprecated-modules=optparse,tkinter.tix + +# Create a graph of external dependencies in the given file (report RP0402 must +# not be disabled). +ext-import-graph= + +# Create a graph of every (i.e. internal and external) dependencies in the +# given file (report RP0402 must not be disabled). +import-graph= + +# Create a graph of internal dependencies in the given file (report RP0402 must +# not be disabled). +int-import-graph= + +# Force import order to recognize a module as part of the standard +# compatibility libraries. +known-standard-library= + +# Force import order to recognize a module as part of a third party library. +known-third-party=enchant + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when being caught. Defaults to +# "BaseException, Exception". +overgeneral-exceptions=BaseException, + Exception diff --git a/app/admin.py b/app/admin.py index 7712358..75166f1 100644 --- a/app/admin.py +++ b/app/admin.py @@ -1,3 +1,5 @@ +"Haldis admin related views and models" + import flask_login as login from flask import Flask from flask_admin import Admin @@ -8,34 +10,43 @@ from models import Location, Order, OrderItem, Product, User class ModelBaseView(ModelView): + "Base model for admin related things" + # pylint: disable=R0201, R0903 def is_accessible(self) -> bool: + "Check if the user has admin permission" if login.current_user.is_anonymous(): return False - return login.current_user.is_admin() class UserAdminModel(ModelBaseView): + "Model for user admin" + # pylint: disable=R0903 column_searchable_list = ("username",) inline_models = None class ProductAdminModel(ModelBaseView): + "Model for product admin" + # pylint: disable=R0903 column_searchable_list = ("name",) inline_models = None class LocationAdminModel(ModelBaseView): + "Model for location admin" + # pylint: disable=R0903 column_searchable_list = ("name", "address", "website") inline_models = None form_columns = ("name", "address", "website", "telephone") -def init_admin(app: Flask, db: SQLAlchemy) -> None: +def init_admin(app: Flask, database: SQLAlchemy) -> None: + "Initialize the admin related things in the app." admin = Admin(app, name="Haldis", url="/admin", template_mode="bootstrap3") - admin.add_view(UserAdminModel(User, db.session)) - admin.add_view(LocationAdminModel(Location, db.session)) - admin.add_view(ProductAdminModel(Product, db.session)) - admin.add_view(ModelBaseView(Order, db.session)) - admin.add_view(ModelBaseView(OrderItem, db.session)) + admin.add_view(UserAdminModel(User, database.session)) + admin.add_view(LocationAdminModel(Location, database.session)) + admin.add_view(ProductAdminModel(Product, database.session)) + admin.add_view(ModelBaseView(Order, database.session)) + admin.add_view(ModelBaseView(OrderItem, database.session)) diff --git a/app/app.py b/app/app.py index 8eec72c..c3e7ab7 100644 --- a/app/app.py +++ b/app/app.py @@ -1,7 +1,8 @@ +"Main Haldis script" import logging +from logging.handlers import TimedRotatingFileHandler import typing from datetime import datetime -from logging.handlers import TimedRotatingFileHandler from airbrake import Airbrake, AirbrakeHandler from flask import Flask, render_template @@ -21,21 +22,24 @@ from zeus import init_oauth def create_app() -> Manager: + "Create the Haldis application" app = Flask(__name__) # Load the config file app.config.from_object("config.Configuration") - manager = register_plugins(app, debug=app.debug) + app_manager = register_plugins(app) add_handlers(app) add_routes(app) add_template_filters(app) # TODO do we need to return and then run the manager? - return manager + return app_manager -def register_plugins(app: Flask, debug: bool) -> Manager: +def register_plugins(app: Flask) -> Manager: + "Register all the plugins to Haldis" + # pylint: disable=W0612 # Register Airbrake and enable the logrotation if not app.debug: timedFileHandler = TimedRotatingFileHandler( @@ -51,11 +55,10 @@ def register_plugins(app: Flask, debug: bool) -> Manager: airbrakelogger = logging.getLogger("airbrake") # Airbrake - airbrake = Airbrake( - project_id=app.config["AIRBRAKE_ID"], api_key=app.config["AIRBRAKE_KEY"] - ) + airbrake = Airbrake(project_id=app.config["AIRBRAKE_ID"], + api_key=app.config["AIRBRAKE_KEY"]) # ugly hack to make this work for out errbit - airbrake._api_url = "http://errbit.awesomepeople.tv/api/v3/projects/{}/notices".format( + airbrake._api_url = "http://errbit.awesomepeople.tv/api/v3/projects/{}/notices".format( # pylint: disable=C0301,W0212 airbrake.project_id ) @@ -67,9 +70,9 @@ def register_plugins(app: Flask, debug: bool) -> Manager: # Initialize Flask-Migrate migrate = Migrate(app, db) - manager = Manager(app) - manager.add_command("db", MigrateCommand) - manager.add_command("runserver", Server(port=8000)) + app_manager = Manager(app) + app_manager.add_command("db", MigrateCommand) + app_manager.add_command("runserver", Server(port=8000)) # Add admin interface init_admin(app, db) @@ -103,10 +106,12 @@ def register_plugins(app: Flask, debug: bool) -> Manager: if not app.debug: app.config.update(SESSION_COOKIE_SECURE=True) - return manager + return app_manager def add_handlers(app: Flask) -> None: + "Add handlers for 4xx error codes" + # pylint: disable=W0612,W0613 @app.errorhandler(404) def handle404(e) -> typing.Tuple[str, int]: return render_template("errors/404.html"), 404 @@ -117,6 +122,7 @@ def add_handlers(app: Flask) -> None: def add_routes(application: Flask) -> None: + "Add all routes to Haldis" # import views # TODO convert to blueprint # import views.stats # TODO convert to blueprint @@ -138,8 +144,12 @@ def add_routes(application: Flask) -> None: def add_template_filters(app: Flask) -> None: + "Add functions which can be used in the templates" + # pylint: disable=W0612 @app.template_filter("countdown") - def countdown(value, only_positive: bool = True, show_text: bool = True) -> str: + def countdown(value, only_positive: bool = True, + show_text: bool = True) -> str: + "A function which returns time until the order is done" delta = value - datetime.now() if delta.total_seconds() < 0 and only_positive: return "closed" @@ -151,12 +161,19 @@ def add_template_filters(app: Flask) -> None: return time @app.template_filter("year") - def current_year(value: typing.Any) -> str: + def current_year(value: typing.Any) -> str: # pylint: disable=W0613 + "A function which returns the current year" return str(datetime.now().year) @app.template_filter("euro") +<<<<<<< HEAD def euro(value: int) -> str: return euro_string(value) +======= + def euro(value: int) -> None: + "A function which converts a value to its euro_string" + euro_string(value) +>>>>>>> Fix pylint for Haldis # For usage when you directly call the script with python diff --git a/app/config.example.py b/app/config.example.py index 48367fc..5b3f500 100644 --- a/app/config.example.py +++ b/app/config.example.py @@ -1,7 +1,10 @@ +"An example for a Haldis config" # config -class Configuration(object): +class Configuration(): + "Haldis configuration object" + # pylint: disable=R0903 SQLALCHEMY_DATABASE_URI = "sqlite:///haldis.db" SQLALCHEMY_TRACK_MODIFICATIONS = False DEBUG = True diff --git a/app/fatmodels.py b/app/fatmodels.py index 79eac01..ac3217e 100644 --- a/app/fatmodels.py +++ b/app/fatmodels.py @@ -28,9 +28,9 @@ class FatOrder(Order, FatModel): @classmethod def items_per_order(cls): return ( - Order.query.join(OrderItem) - .group_by(Order.id) - .with_entities(Order.id, func.count(OrderItem.user_id).label("total")) + Order.query.join(OrderItem).group_by(Order.id) + .with_entities(Order.id, + func.count(OrderItem.user_id).label("total")) ) @@ -50,7 +50,8 @@ class FatProduct(Product, FatModel): .join(Location) .group_by(Product.id) .with_entities( - Product.name, Location.name, func.count(Product.id).label("count") + Product.name, Location.name, func.count( + Product.id).label("count") ) .order_by(desc("count")) .limit(4) diff --git a/app/forms.py b/app/forms.py index 4003944..e75893a 100644 --- a/app/forms.py +++ b/app/forms.py @@ -1,3 +1,4 @@ +"Script for everything form related in Haldis" from datetime import datetime, timedelta from flask import session @@ -11,6 +12,8 @@ from utils import euro_string class OrderForm(Form): + "Class which defines the form for a new Order" + # pylint: disable=R0903 courrier_id = SelectField("Courrier", coerce=int) location_id = SelectField( "Location", coerce=int, validators=[validators.required()] @@ -22,6 +25,7 @@ class OrderForm(Form): submit_button = SubmitField("Submit") def populate(self) -> None: + "Fill in the options for courrier for an Order" if current_user.is_admin(): self.courrier_id.choices = [(0, None)] + [ (u.id, u.username) for u in User.query.order_by("username") @@ -39,25 +43,38 @@ class OrderForm(Form): class OrderItemForm(Form): + "Class which defines the form for a new Item in an Order" + # pylint: disable=R0903 product_id = SelectField("Item", coerce=int) extra = StringField("Extra") submit_button = SubmitField("Submit") def populate(self, location: Location) -> None: + "Fill in all the product options from the location" self.product_id.choices = [ - (i.id, (i.name + ": " + euro_string(i.price))) for i in location.products + (i.id, (i.name + ": " + euro_string(i.price))) + for i in location.products ] class AnonOrderItemForm(OrderItemForm): + """ + Class which defines the form for a new Item in an Order + For Users who aren't logged in + """ name = StringField("Name", validators=[validators.required()]) def populate(self, location: Location) -> None: + """ + Fill in all the product options from the location and + the name of the anon user + """ OrderItemForm.populate(self, location) if self.name.data is None: self.name.data = session.get("anon_name", None) def validate(self) -> bool: + "Check if the provided anon_name is not already taken" rv = OrderForm.validate(self) if not rv: return False diff --git a/app/login.py b/app/login.py index c50b245..984ee4f 100644 --- a/app/login.py +++ b/app/login.py @@ -1,3 +1,4 @@ +"Script for everything related to logging in and out" from flask import Blueprint, abort, redirect, session, url_for from flask_login import current_user, logout_user from werkzeug.wrappers import Response @@ -9,18 +10,23 @@ auth_bp = Blueprint("auth_bp", __name__) def init_login(app) -> None: + "Initialize the login" + # pylint: disable=W0612 @app.login_manager.user_loader def load_user(userid) -> User: + "Load the user" return User.query.filter_by(id=userid).first() @auth_bp.route("/login") def login(): + "Function to handle a user trying to log in" return zeus_login() @auth_bp.route("/logout") def logout() -> Response: + "Function to handle a user trying to log out" if "zeus_token" in session: session.pop("zeus_token", None) logout_user() @@ -28,5 +34,6 @@ def logout() -> Response: def before_request() -> None: + "Function for what has to be done before a request" if current_user.is_anonymous() or not current_user.is_allowed(): abort(401) diff --git a/app/migrations/env.py b/app/migrations/env.py index f416a43..3cd65b9 100644 --- a/app/migrations/env.py +++ b/app/migrations/env.py @@ -1,3 +1,4 @@ +"Script that runs migrations online or offline" from __future__ import with_statement from logging.config import fileConfig diff --git a/app/notification.py b/app/notification.py index 622f920..d12047b 100644 --- a/app/notification.py +++ b/app/notification.py @@ -1,3 +1,4 @@ +"Script that handles Haldis notifications on chat platforms" import json from datetime import datetime from threading import Thread @@ -8,19 +9,22 @@ from flask import url_for def post_order_to_webhook(order_item) -> None: + "Function that sends the notification for the order" message = "" if order_item.courrier is not None: - message = " {3} is going to {1}, order <{0}|here>! Deadline in {2} minutes!".format( - url_for("order_bp.order_from_id", order_id=order_item.id, _external=True), + message = " {3} is going to {1}, order <{0}|here>! Deadline in {2} minutes!".format( # pylint: disable=C0301 + url_for("order_bp.order_from_id", order_id=order_item.id, + _external=True), order_item.location.name, remaining_minutes(order_item.stoptime), order_item.courrier.username.title(), ) else: - message = " New order for {}. Deadline in {} minutes. <{}|Open here.>".format( + message = " New order for {}. Deadline in {} minutes. <{}|Open here.>".format( # pylint: disable=C0301 order_item.location.name, remaining_minutes(order_item.stoptime), - url_for("order_bp.order_from_id", order_id=order_item.id, _external=True), + url_for("order_bp.order_from_id", + order_id=order_item.id, _external=True), ) webhookthread = WebhookSenderThread(message, app.config["SLACK_WEBHOOK"]) webhookthread.start() @@ -28,6 +32,7 @@ def post_order_to_webhook(order_item) -> None: class WebhookSenderThread(Thread): def __init__(self, message: str, url: str) -> None: + "Extension of the Thread class, which sends a webhook for the notification" super(WebhookSenderThread, self).__init__() self.message = message self.url = url @@ -36,6 +41,7 @@ class WebhookSenderThread(Thread): self.slack_webhook() def slack_webhook(self) -> None: + "The webhook for the specified chat platform" if self.url: requests.post(url, json={"text": self.message}) else: @@ -43,6 +49,7 @@ class WebhookSenderThread(Thread): def remaining_minutes(value) -> str: + "Return the remaining minutes until the deadline of and order" delta = value - datetime.now() if delta.total_seconds() < 0: return "0" diff --git a/app/passenger_wsgi.py b/app/passenger_wsgi.py index 5e2534c..ad4cdd2 100644 --- a/app/passenger_wsgi.py +++ b/app/passenger_wsgi.py @@ -1,4 +1,5 @@ #!/usr/bin/env python3 +"Script to run Haldis on a server" import os import sys diff --git a/app/utils.py b/app/utils.py index 1584117..d9b0f38 100644 --- a/app/utils.py +++ b/app/utils.py @@ -1,3 +1,6 @@ +"Script which contains several utils for Haldis" + + def euro_string(value: int) -> str: """ Convert cents to string formatted euro diff --git a/app/zeus.py b/app/zeus.py index 8ca77d1..7ef0a6a 100644 --- a/app/zeus.py +++ b/app/zeus.py @@ -1,3 +1,4 @@ +"Script containing everything specific to ZeusWPI" import typing from flask import (Blueprint, current_app, flash, redirect, request, session, @@ -12,6 +13,7 @@ oauth_bp = Blueprint("oauth_bp", __name__) def zeus_login(): + "Log in using ZeusWPI" return current_app.zeus.authorize( callback=url_for("oauth_bp.authorized", _external=True) ) @@ -21,6 +23,7 @@ def zeus_login(): def authorized() -> typing.Any: # type is 'typing.Union[str, Response]', but this errors due to # https://github.com/python/mypy/issues/7187 + "Check authorized status" resp = current_app.zeus.authorized_response() if resp is None: return "Access denied: reason=%s error=%s" % ( @@ -35,9 +38,10 @@ def authorized() -> typing.Any: username = me.data.get("username", "").lower() user = User.query.filter_by(username=username).first() - if len(username) > 0 and user: + # pylint: disable=R1705 + if username and user: return login_and_redirect_user(user) - elif len(username) > 0: + elif username > 0: user = create_user(username) return login_and_redirect_user(user) @@ -46,6 +50,7 @@ def authorized() -> typing.Any: def init_oauth(app): + "Initialize the OAuth for ZeusWPI" oauth = OAuth(app) zeus = oauth.remote_app( @@ -59,6 +64,7 @@ def init_oauth(app): authorize_url="https://adams.ugent.be/oauth/oauth2/authorize/", ) + # pylint: disable=W0612 @zeus.tokengetter def get_zeus_oauth_token(): return session.get("zeus_token") @@ -67,11 +73,13 @@ def init_oauth(app): def login_and_redirect_user(user) -> Response: + "Log in the user and then redirect them" login_user(user) return redirect(url_for("general_bp.home")) def create_user(username) -> User: + "Create a temporary user if it is needed" user = User() user.configure(username, False, 1) db.session.add(user) From 0af72376a10cbf71b2b6183a8afcff464cae59b9 Mon Sep 17 00:00:00 2001 From: Midgard Date: Wed, 11 Sep 2019 16:01:49 +0200 Subject: [PATCH 5/6] Increase line length limit to 100 Up from 80. --- .pylintrc | 2 +- app/app.py | 2 +- app/database/create_database.py | 8 ++++---- app/models/__init__.py | 6 +++--- app/views/order.py | 2 +- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/.pylintrc b/.pylintrc index cf85192..1f6b81c 100644 --- a/.pylintrc +++ b/.pylintrc @@ -375,7 +375,7 @@ indent-after-paren=4 indent-string=' ' # Maximum number of characters on a single line. -max-line-length=80 +max-line-length=100 # Maximum number of lines in a module. max-module-lines=1000 diff --git a/app/app.py b/app/app.py index c3e7ab7..3273dd0 100644 --- a/app/app.py +++ b/app/app.py @@ -58,7 +58,7 @@ def register_plugins(app: Flask) -> Manager: airbrake = Airbrake(project_id=app.config["AIRBRAKE_ID"], api_key=app.config["AIRBRAKE_KEY"]) # ugly hack to make this work for out errbit - airbrake._api_url = "http://errbit.awesomepeople.tv/api/v3/projects/{}/notices".format( # pylint: disable=C0301,W0212 + airbrake._api_url = "http://errbit.awesomepeople.tv/api/v3/projects/{}/notices".format( # pylint: disable=W0212 airbrake.project_id ) diff --git a/app/database/create_database.py b/app/database/create_database.py index 128af81..46ea197 100644 --- a/app/database/create_database.py +++ b/app/database/create_database.py @@ -39,9 +39,9 @@ def add_all() -> None: def recreate_from_scratch() -> None: "Recreate a completely new database" - confirmation = "Are you very very sure? (Will delete previous entries!) (y/N) " # pylint: disable=C0301 + confirmation = "Are you very very sure? (Will delete previous entries!) (y/N) " check = "I acknowledge any repercussions!" - if input(confirmation) in yes and input("Type: '{}' ".format(check)) == check: # pylint: disable=C0301 + if input(confirmation) in yes and input("Type: '{}' ".format(check)) == check: print("Resetting the database!") db.drop_all() db.create_all() @@ -58,14 +58,14 @@ def add_to_current() -> None: ).rstrip(", ") while input("Do you still want to add something? (Y/n) ") not in no: - print("What do you want to add? (Use numbers, or A for all, or C for cancel) ") # pylint: disable=C0301 + print("What do you want to add? (Use numbers, or A for all, or C for cancel) ") answer = input("Available: {} : ".format(add_numbers())) if answer == "A": add_all() available = [] elif answer == "C": pass - elif answer.isnumeric() and answer in [str(x) for x in range(len(available))]: # pylint: disable=C0301 + elif answer.isnumeric() and answer in [str(x) for x in range(len(available))]: answer_index = int(answer) print("Adding {}.".format(available[answer_index])) entry_sets[str(available[answer_index])]() diff --git a/app/models/__init__.py b/app/models/__init__.py index 4fcaf0a..210c8d3 100644 --- a/app/models/__init__.py +++ b/app/models/__init__.py @@ -1,7 +1,7 @@ "The base file for everything related to the models" -# pylint: disable=C0301 -# This file will expose what we want from the models module -# This will probably be everything. But putting the imports here makes it possible to import all models in one line like this: +# This file will expose what we want from the models module. +# This will probably be everything. But putting the imports here makes it possible to import all +# models in one line like this: # # from models import User, Item, ... # diff --git a/app/views/order.py b/app/views/order.py index ad0cae9..f96e848 100644 --- a/app/views/order.py +++ b/app/views/order.py @@ -147,7 +147,7 @@ def item_paid(order_id: int, item_id: int) -> typing.Optional[Response]: @order_bp.route("///user_paid", methods=["POST"]) @login_required # pylint: disable=R1710 -def items_user_paid(order_id: int, user_name: str) -> typing.Optional[Response]: # pylint:disable=C0301 +def items_user_paid(order_id: int, user_name: str) -> typing.Optional[Response]: "Indicate payment status for a user in an order" user = User.query.filter(User.username == user_name).first() items: typing.List[OrderItem] = [] From f394fb79119833b50d655a0a577c4aa5941be8a7 Mon Sep 17 00:00:00 2001 From: Jan-Pieter Baert Date: Fri, 13 Sep 2019 16:51:38 +0200 Subject: [PATCH 6/6] Fix unresolved merge conflict --- app/app.py | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/app/app.py b/app/app.py index 3273dd0..9788e36 100644 --- a/app/app.py +++ b/app/app.py @@ -166,14 +166,9 @@ def add_template_filters(app: Flask) -> None: return str(datetime.now().year) @app.template_filter("euro") -<<<<<<< HEAD def euro(value: int) -> str: - return euro_string(value) -======= - def euro(value: int) -> None: "A function which converts a value to its euro_string" - euro_string(value) ->>>>>>> Fix pylint for Haldis + return euro_string(value) # For usage when you directly call the script with python