Merge pull request #142 from ZeusWPI/fix-pylint-formatting
Fix pylint formatting for Haldis
This commit is contained in:
commit
112cafecbb
37 changed files with 776 additions and 129 deletions
492
.pylintrc
Normal file
492
.pylintrc
Normal file
|
@ -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*(# )?<?https?://\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
|
25
app/admin.py
25
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))
|
||||
|
|
40
app/app.py
40
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)
|
||||
|
||||
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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",
|
||||
|
|
|
@ -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)",
|
||||
|
|
|
@ -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",
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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():
|
||||
|
|
|
@ -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)
|
||||
|
|
19
app/forms.py
19
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
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
"Script that runs migrations online or offline"
|
||||
from __future__ import with_statement
|
||||
|
||||
from logging.config import fileConfig
|
||||
|
|
|
@ -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, ...
|
||||
#
|
||||
|
|
|
@ -1,3 +1,7 @@
|
|||
"AnonymouseUser for people who are not logged in the normal way"
|
||||
# pylint: disable=R0201,C0111
|
||||
|
||||
|
||||
class AnonymouseUser:
|
||||
id = None
|
||||
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
# pylint: disable=C0111
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
|
||||
db = SQLAlchemy()
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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():
|
||||
|
|
|
@ -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",)
|
||||
|
|
|
@ -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
|
||||
|
||||
|
|
|
@ -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 "<!channel|@channel> {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"
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
#!/usr/bin/env python3
|
||||
"Script to run Haldis on a server"
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
|
|
@ -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'),
|
||||
] -%}
|
||||
|
|
|
@ -14,7 +14,7 @@
|
|||
<tbody>
|
||||
{% for loc in locations -%}
|
||||
<tr>
|
||||
<td><a href="{{ url_for('general_bp.location', id=loc.id) }}">{{ loc.name }}</a></td>
|
||||
<td><a href="{{ url_for('general_bp.location', location_id=loc.id) }}">{{ loc.name }}</a></td>
|
||||
<td>{{ loc.address }}<td>
|
||||
<td><a href="{{ loc.website}}"><span class="glyphicon glyphicon-link"></span></a></td>
|
||||
<td>
|
||||
|
|
|
@ -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);
|
||||
|
||||
|
|
|
@ -11,16 +11,16 @@
|
|||
<h3 id="order-title">Order {{ order.id }}
|
||||
<div class="pull-right">
|
||||
{% if order.can_close(current_user.id) -%}
|
||||
<form action="{{ url_for('order_bp.close_order', id=order.id) }}" method="post" style="display:inline">
|
||||
<form action="{{ url_for('order_bp.close_order', order_id=order.id) }}" method="post" style="display:inline">
|
||||
<input type="submit" class="btn btn-danger" value="Close"></input>
|
||||
</form>
|
||||
{% endif %}{% if courier_or_admin %}
|
||||
<a class="btn btn-warning" href="{{ url_for('order_bp.order_edit', id=order.id) }}">Edit</a>
|
||||
<a class="btn btn-warning" href="{{ url_for('order_bp.order_edit', order_id=order.id) }}">Edit</a>
|
||||
{%- endif %}
|
||||
</div></h3>
|
||||
courier: {{ order.courrier.username }}
|
||||
{% if order.courrier == None and not current_user.is_anonymous() %}
|
||||
<form action="{{ url_for('order_bp.volunteer', id=order.id) }}" method="post" style="display:inline">
|
||||
<form action="{{ url_for('order_bp.volunteer', order_id=order.id) }}" method="post" style="display:inline">
|
||||
<input type="submit" class="btn btn-primary btn-sm" value="Volunteer"></input>
|
||||
</form>
|
||||
{% endif %}
|
||||
|
@ -38,7 +38,7 @@
|
|||
{% if form -%}
|
||||
<div class="col-md-push-1 col-md-10 darker" id="form">
|
||||
<h4>Order:</h4>
|
||||
<form method="post" action="{{ url_for('order_bp.order_item_create', id=order.id) }}">
|
||||
<form method="post" action="{{ url_for('order_bp.order_item_create', order_id=order.id) }}">
|
||||
<span class="pull-right">
|
||||
<a class="btn btn-primary" onclick="chooseRandom()">Choose for me</a>
|
||||
</span>
|
||||
|
@ -99,7 +99,7 @@
|
|||
</div>
|
||||
<div class="col-md-push-2 col-md-4 darker box" id="items-ordered">
|
||||
<h3>Ordered products: {{ order.items.count() }}</h3>
|
||||
<a class="divLink" href="{{ url_for('order_bp.items_showcase', id=order.id) }}"></a>
|
||||
<a class="divLink" href="{{ url_for('order_bp.items_showcase', order_id=order.id) }}"></a>
|
||||
{% for key, value in order.group_by_product().items() -%}
|
||||
<div class="product">
|
||||
{{ key }}: {{ value["count"] }}
|
||||
|
|
|
@ -11,7 +11,7 @@
|
|||
<h3>Edit order:</h3>
|
||||
<div class="row darker">
|
||||
<div class="col-sm-12">
|
||||
<form method="post" action="{{ url_for('.order_edit', id=order_id) }}">
|
||||
<form method="post" action="{{ url_for('.order_edit', order_id=order_id) }}">
|
||||
{{ form.csrf_token }}
|
||||
<div class="form-group select2 {{ 'has-errors' if form.courrier_id.errors else ''}}">
|
||||
{{ form.courrier_id.label(class='control-label') }}<br>
|
||||
|
|
|
@ -9,7 +9,7 @@
|
|||
<b>Orders:</b> {{ order.items.count() }}</p>
|
||||
</div>
|
||||
<div class="col-md-4 col-lg-3">
|
||||
<a class="btn btn-primary btn-block align-bottom" href="{{ url_for('order_bp.order', id=order.id) }}">Expand</a>
|
||||
<a class="btn btn-primary btn-block align-bottom" href="{{ url_for('order_bp.order', order_id=order.id) }}">Expand</a>
|
||||
</div>
|
||||
</div>
|
||||
{%- endmacro %}
|
||||
|
|
|
@ -1,3 +1,6 @@
|
|||
"Script which contains several utils for Haldis"
|
||||
|
||||
|
||||
def euro_string(value: int) -> str:
|
||||
"""
|
||||
Convert cents to string formatted euro
|
||||
|
|
|
@ -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 = []
|
||||
|
|
|
@ -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/<int:id>")
|
||||
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/<int:id>")
|
||||
def location(id) -> str:
|
||||
loc = Location.query.filter(Location.id == id).first()
|
||||
@general_bp.route("/location/<int:location_id>")
|
||||
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",
|
||||
|
|
|
@ -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("/<id>")
|
||||
def order(id: int, form: OrderForm = None) -> str:
|
||||
order = Order.query.filter(Order.id == id).first()
|
||||
@order_bp.route("/<order_id>")
|
||||
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("/<id>/items")
|
||||
def items_showcase(id: int, form: OrderForm = None) -> str:
|
||||
order = Order.query.filter(Order.id == id).first()
|
||||
@order_bp.route("/<order_id>/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("/<id>/edit", methods=["GET", "POST"])
|
||||
@order_bp.route("/<order_id>/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("/<id>/create", methods=["POST"])
|
||||
def order_item_create(id: int) -> typing.Any:
|
||||
@order_bp.route("/<order_id>/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("/<order_id>/<item_id>/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("/<order_id>/<user_name>/user_paid", methods=["POST"])
|
||||
@login_required
|
||||
# pylint: disable=R1710
|
||||
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] = []
|
||||
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("/<order_id>/<item_id>/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("/<id>/volunteer", methods=["POST"])
|
||||
@order_bp.route("/<order_id>/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("/<id>/close", methods=["POST"])
|
||||
@order_bp.route("/<order_id>/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
|
||||
|
|
|
@ -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(),
|
||||
|
|
12
app/zeus.py
12
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)
|
||||
|
|
Loading…
Reference in a new issue