diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 0000000..1f6b81c --- /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=100 + +# 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..9788e36 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=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,11 +161,13 @@ 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") def euro(value: int) -> str: + "A function which converts a value to its euro_string" return euro_string(value) 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/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 74c0a48..dbc43f5 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 @@ -19,24 +20,27 @@ yes = ["yes", "y"] no = ["no", "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.lower() 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: + "Recreate a completely new database" confirmation = "Are you very very sure? (Will delete previous entries!) (y/N) " if input(confirmation) in yes: print("Resetting the database!") @@ -48,6 +52,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: @@ -77,7 +82,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(): 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/models/__init__.py b/app/models/__init__.py index 60576f2..210c8d3 100644 --- a/app/models/__init__.py +++ b/app/models/__init__.py @@ -1,5 +1,7 @@ -# 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: +"The base file for everything related to the models" +# 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/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 6bcaa13..06b62c1 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 diff --git a/app/notification.py b/app/notification.py index 2637e76..ec55454 100644 --- a/app/notification.py +++ b/app/notification.py @@ -1,3 +1,4 @@ +"Script that handles Haldis notifications on chat platforms" import json import typing from datetime import datetime @@ -10,10 +11,12 @@ from models.order import Order def webhook_text(order_item: Order) -> typing.Optional[str]: + "Function that makes the text for the notification" if "Testlocation" in order_item.location.name: return None if order_item.courrier is not None: + # pylint: disable=C0301 return " {3} is going to {1}, order <{0}|here>! Deadline in {2} minutes!".format( url_for("order_bp.order", id=order_item.id, _external=True), order_item.location.name, @@ -29,13 +32,17 @@ def webhook_text(order_item: Order) -> typing.Optional[str]: def post_order_to_webhook(order_item: Order) -> None: + "Function that sends the notification for the order" message = webhook_text(order_item) if message: - webhookthread = WebhookSenderThread(message, app.config["SLACK_WEBHOOK"]) + webhookthread = WebhookSenderThread( + message, app.config["SLACK_WEBHOOK"]) webhookthread.start() class WebhookSenderThread(Thread): + "Extension of the Thread class, which sends a webhook for the notification" + def __init__(self, message: str, url: str) -> None: super(WebhookSenderThread, self).__init__() self.message = message @@ -45,6 +52,7 @@ class WebhookSenderThread(Thread): self.slack_webhook() def slack_webhook(self) -> None: + "The webhook for the specified chat platform" if self.url: requests.post(self.url, json={"text": self.message}) else: @@ -52,6 +60,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/templates/layout.html b/app/templates/layout.html index 98a85b3..c658c82 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 -%}