Fix pylint for Haldis

This commit is contained in:
Jan-Pieter Baert 2019-09-10 15:17:35 +02:00
parent c4f9222558
commit 48641adf90
No known key found for this signature in database
GPG key ID: B19186932178234A
12 changed files with 601 additions and 33 deletions

492
.pylintrc Normal file
View 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=80
# Maximum number of lines in a module.
max-module-lines=1000
# List of optional constructs for which whitespace checking is disabled. `dict-
# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}.
# `trailing-comma` allows a space between comma and closing bracket: (a, ).
# `empty-line` allows space-only lines.
no-space-check=trailing-comma,
dict-separator
# Allow the body of a class to be on the same line as the declaration if body
# contains single statement.
single-line-class-stmt=no
# Allow the body of an if to be on the same line as the test if there is no
# else.
single-line-if-stmt=no
[DESIGN]
# Maximum number of arguments for function / method.
max-args=5
# Maximum number of attributes for a class (see R0902).
max-attributes=7
# Maximum number of boolean expressions in an if statement.
max-bool-expr=5
# Maximum number of branch for function / method body.
max-branches=12
# Maximum number of locals for function / method body.
max-locals=15
# Maximum number of parents for a class (see R0901).
max-parents=7
# Maximum number of public methods for a class (see R0904).
max-public-methods=20
# Maximum number of return / yield for function / method body.
max-returns=6
# Maximum number of statements in function / method body.
max-statements=50
# Minimum number of public methods for a class (see R0903).
min-public-methods=2
[CLASSES]
# List of method names used to declare (i.e. assign) instance attributes.
defining-attr-methods=__init__,
__new__,
setUp
# List of member names, which should be excluded from the protected access
# warning.
exclude-protected=_asdict,
_fields,
_replace,
_source,
_make
# List of valid names for the first argument in a class method.
valid-classmethod-first-arg=cls
# List of valid names for the first argument in a metaclass class method.
valid-metaclass-classmethod-first-arg=cls
[IMPORTS]
# Allow wildcard imports from modules that define __all__.
allow-wildcard-with-all=no
# Analyse import fallback blocks. This can be used to support both Python 2 and
# 3 compatible code, which means that the block might have code that exists
# only in one or another interpreter, leading to false positives when analysed.
analyse-fallback-blocks=no
# Deprecated modules which should not be used, separated by a comma.
deprecated-modules=optparse,tkinter.tix
# Create a graph of external dependencies in the given file (report RP0402 must
# not be disabled).
ext-import-graph=
# Create a graph of every (i.e. internal and external) dependencies in the
# given file (report RP0402 must not be disabled).
import-graph=
# Create a graph of internal dependencies in the given file (report RP0402 must
# not be disabled).
int-import-graph=
# Force import order to recognize a module as part of the standard
# compatibility libraries.
known-standard-library=
# Force import order to recognize a module as part of a third party library.
known-third-party=enchant
[EXCEPTIONS]
# Exceptions that will emit a warning when being caught. Defaults to
# "BaseException, Exception".
overgeneral-exceptions=BaseException,
Exception

View file

@ -1,3 +1,5 @@
"Haldis admin related views and models"
import flask_login as login import flask_login as login
from flask import Flask from flask import Flask
from flask_admin import Admin from flask_admin import Admin
@ -8,34 +10,43 @@ from models import Location, Order, OrderItem, Product, User
class ModelBaseView(ModelView): class ModelBaseView(ModelView):
"Base model for admin related things"
# pylint: disable=R0201, R0903
def is_accessible(self) -> bool: def is_accessible(self) -> bool:
"Check if the user has admin permission"
if login.current_user.is_anonymous(): if login.current_user.is_anonymous():
return False return False
return login.current_user.is_admin() return login.current_user.is_admin()
class UserAdminModel(ModelBaseView): class UserAdminModel(ModelBaseView):
"Model for user admin"
# pylint: disable=R0903
column_searchable_list = ("username",) column_searchable_list = ("username",)
inline_models = None inline_models = None
class ProductAdminModel(ModelBaseView): class ProductAdminModel(ModelBaseView):
"Model for product admin"
# pylint: disable=R0903
column_searchable_list = ("name",) column_searchable_list = ("name",)
inline_models = None inline_models = None
class LocationAdminModel(ModelBaseView): class LocationAdminModel(ModelBaseView):
"Model for location admin"
# pylint: disable=R0903
column_searchable_list = ("name", "address", "website") column_searchable_list = ("name", "address", "website")
inline_models = None inline_models = None
form_columns = ("name", "address", "website", "telephone") 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 = Admin(app, name="Haldis", url="/admin", template_mode="bootstrap3")
admin.add_view(UserAdminModel(User, db.session)) admin.add_view(UserAdminModel(User, database.session))
admin.add_view(LocationAdminModel(Location, db.session)) admin.add_view(LocationAdminModel(Location, database.session))
admin.add_view(ProductAdminModel(Product, db.session)) admin.add_view(ProductAdminModel(Product, database.session))
admin.add_view(ModelBaseView(Order, db.session)) admin.add_view(ModelBaseView(Order, database.session))
admin.add_view(ModelBaseView(OrderItem, db.session)) admin.add_view(ModelBaseView(OrderItem, database.session))

View file

@ -1,7 +1,8 @@
"Main Haldis script"
import logging import logging
from logging.handlers import TimedRotatingFileHandler
import typing import typing
from datetime import datetime from datetime import datetime
from logging.handlers import TimedRotatingFileHandler
from airbrake import Airbrake, AirbrakeHandler from airbrake import Airbrake, AirbrakeHandler
from flask import Flask, render_template from flask import Flask, render_template
@ -21,21 +22,24 @@ from zeus import init_oauth
def create_app() -> Manager: def create_app() -> Manager:
"Create the Haldis application"
app = Flask(__name__) app = Flask(__name__)
# Load the config file # Load the config file
app.config.from_object("config.Configuration") app.config.from_object("config.Configuration")
manager = register_plugins(app, debug=app.debug) app_manager = register_plugins(app)
add_handlers(app) add_handlers(app)
add_routes(app) add_routes(app)
add_template_filters(app) add_template_filters(app)
# TODO do we need to return and then run the manager? # 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 # Register Airbrake and enable the logrotation
if not app.debug: if not app.debug:
timedFileHandler = TimedRotatingFileHandler( timedFileHandler = TimedRotatingFileHandler(
@ -51,11 +55,10 @@ def register_plugins(app: Flask, debug: bool) -> Manager:
airbrakelogger = logging.getLogger("airbrake") airbrakelogger = logging.getLogger("airbrake")
# Airbrake # Airbrake
airbrake = Airbrake( airbrake = Airbrake(project_id=app.config["AIRBRAKE_ID"],
project_id=app.config["AIRBRAKE_ID"], api_key=app.config["AIRBRAKE_KEY"] api_key=app.config["AIRBRAKE_KEY"])
)
# ugly hack to make this work for out errbit # ugly hack to make this work for out errbit
airbrake._api_url = "http://errbit.awesomepeople.tv/api/v3/projects/{}/notices".format( airbrake._api_url = "http://errbit.awesomepeople.tv/api/v3/projects/{}/notices".format( # pylint: disable=C0301,W0212
airbrake.project_id airbrake.project_id
) )
@ -67,9 +70,9 @@ def register_plugins(app: Flask, debug: bool) -> Manager:
# Initialize Flask-Migrate # Initialize Flask-Migrate
migrate = Migrate(app, db) migrate = Migrate(app, db)
manager = Manager(app) app_manager = Manager(app)
manager.add_command("db", MigrateCommand) app_manager.add_command("db", MigrateCommand)
manager.add_command("runserver", Server(port=8000)) app_manager.add_command("runserver", Server(port=8000))
# Add admin interface # Add admin interface
init_admin(app, db) init_admin(app, db)
@ -103,10 +106,12 @@ def register_plugins(app: Flask, debug: bool) -> Manager:
if not app.debug: if not app.debug:
app.config.update(SESSION_COOKIE_SECURE=True) app.config.update(SESSION_COOKIE_SECURE=True)
return manager return app_manager
def add_handlers(app: Flask) -> None: def add_handlers(app: Flask) -> None:
"Add handlers for 4xx error codes"
# pylint: disable=W0612,W0613
@app.errorhandler(404) @app.errorhandler(404)
def handle404(e) -> typing.Tuple[str, int]: def handle404(e) -> typing.Tuple[str, int]:
return render_template("errors/404.html"), 404 return render_template("errors/404.html"), 404
@ -117,6 +122,7 @@ def add_handlers(app: Flask) -> None:
def add_routes(application: Flask) -> None: def add_routes(application: Flask) -> None:
"Add all routes to Haldis"
# import views # TODO convert to blueprint # import views # TODO convert to blueprint
# import views.stats # 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: def add_template_filters(app: Flask) -> None:
"Add functions which can be used in the templates"
# pylint: disable=W0612
@app.template_filter("countdown") @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() delta = value - datetime.now()
if delta.total_seconds() < 0 and only_positive: if delta.total_seconds() < 0 and only_positive:
return "closed" return "closed"
@ -151,12 +161,19 @@ def add_template_filters(app: Flask) -> None:
return time return time
@app.template_filter("year") @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) return str(datetime.now().year)
@app.template_filter("euro") @app.template_filter("euro")
<<<<<<< HEAD
def euro(value: int) -> str: def euro(value: int) -> str:
return euro_string(value) return euro_string(value)
=======
def euro(value: int) -> None:
"A function which converts a value to its euro_string"
euro_string(value)
>>>>>>> Fix pylint for Haldis
# For usage when you directly call the script with python # For usage when you directly call the script with python

View file

@ -1,7 +1,10 @@
"An example for a Haldis config"
# config # config
class Configuration(object): class Configuration():
"Haldis configuration object"
# pylint: disable=R0903
SQLALCHEMY_DATABASE_URI = "sqlite:///haldis.db" SQLALCHEMY_DATABASE_URI = "sqlite:///haldis.db"
SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_TRACK_MODIFICATIONS = False
DEBUG = True DEBUG = True

View file

@ -28,9 +28,9 @@ class FatOrder(Order, FatModel):
@classmethod @classmethod
def items_per_order(cls): def items_per_order(cls):
return ( return (
Order.query.join(OrderItem) Order.query.join(OrderItem).group_by(Order.id)
.group_by(Order.id) .with_entities(Order.id,
.with_entities(Order.id, func.count(OrderItem.user_id).label("total")) func.count(OrderItem.user_id).label("total"))
) )
@ -50,7 +50,8 @@ class FatProduct(Product, FatModel):
.join(Location) .join(Location)
.group_by(Product.id) .group_by(Product.id)
.with_entities( .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")) .order_by(desc("count"))
.limit(4) .limit(4)

View file

@ -1,3 +1,4 @@
"Script for everything form related in Haldis"
from datetime import datetime, timedelta from datetime import datetime, timedelta
from flask import session from flask import session
@ -11,6 +12,8 @@ from utils import euro_string
class OrderForm(Form): class OrderForm(Form):
"Class which defines the form for a new Order"
# pylint: disable=R0903
courrier_id = SelectField("Courrier", coerce=int) courrier_id = SelectField("Courrier", coerce=int)
location_id = SelectField( location_id = SelectField(
"Location", coerce=int, validators=[validators.required()] "Location", coerce=int, validators=[validators.required()]
@ -22,6 +25,7 @@ class OrderForm(Form):
submit_button = SubmitField("Submit") submit_button = SubmitField("Submit")
def populate(self) -> None: def populate(self) -> None:
"Fill in the options for courrier for an Order"
if current_user.is_admin(): if current_user.is_admin():
self.courrier_id.choices = [(0, None)] + [ self.courrier_id.choices = [(0, None)] + [
(u.id, u.username) for u in User.query.order_by("username") (u.id, u.username) for u in User.query.order_by("username")
@ -39,25 +43,38 @@ class OrderForm(Form):
class OrderItemForm(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) product_id = SelectField("Item", coerce=int)
extra = StringField("Extra") extra = StringField("Extra")
submit_button = SubmitField("Submit") submit_button = SubmitField("Submit")
def populate(self, location: Location) -> None: def populate(self, location: Location) -> None:
"Fill in all the product options from the location"
self.product_id.choices = [ 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 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()]) name = StringField("Name", validators=[validators.required()])
def populate(self, location: Location) -> None: 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) OrderItemForm.populate(self, location)
if self.name.data is None: if self.name.data is None:
self.name.data = session.get("anon_name", None) self.name.data = session.get("anon_name", None)
def validate(self) -> bool: def validate(self) -> bool:
"Check if the provided anon_name is not already taken"
rv = OrderForm.validate(self) rv = OrderForm.validate(self)
if not rv: if not rv:
return False return False

View file

@ -1,3 +1,4 @@
"Script for everything related to logging in and out"
from flask import Blueprint, abort, redirect, session, url_for from flask import Blueprint, abort, redirect, session, url_for
from flask_login import current_user, logout_user from flask_login import current_user, logout_user
from werkzeug.wrappers import Response from werkzeug.wrappers import Response
@ -9,18 +10,23 @@ auth_bp = Blueprint("auth_bp", __name__)
def init_login(app) -> None: def init_login(app) -> None:
"Initialize the login"
# pylint: disable=W0612
@app.login_manager.user_loader @app.login_manager.user_loader
def load_user(userid) -> User: def load_user(userid) -> User:
"Load the user"
return User.query.filter_by(id=userid).first() return User.query.filter_by(id=userid).first()
@auth_bp.route("/login") @auth_bp.route("/login")
def login(): def login():
"Function to handle a user trying to log in"
return zeus_login() return zeus_login()
@auth_bp.route("/logout") @auth_bp.route("/logout")
def logout() -> Response: def logout() -> Response:
"Function to handle a user trying to log out"
if "zeus_token" in session: if "zeus_token" in session:
session.pop("zeus_token", None) session.pop("zeus_token", None)
logout_user() logout_user()
@ -28,5 +34,6 @@ def logout() -> Response:
def before_request() -> None: 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(): if current_user.is_anonymous() or not current_user.is_allowed():
abort(401) abort(401)

View file

@ -1,3 +1,4 @@
"Script that runs migrations online or offline"
from __future__ import with_statement from __future__ import with_statement
from logging.config import fileConfig from logging.config import fileConfig

View file

@ -1,3 +1,4 @@
"Script that handles Haldis notifications on chat platforms"
import json import json
from datetime import datetime from datetime import datetime
from threading import Thread from threading import Thread
@ -8,19 +9,22 @@ from flask import url_for
def post_order_to_webhook(order_item) -> None: def post_order_to_webhook(order_item) -> None:
"Function that sends the notification for the order"
message = "" message = ""
if order_item.courrier is not None: if order_item.courrier is not None:
message = "<!channel|@channel> {3} is going to {1}, order <{0}|here>! Deadline in {2} minutes!".format( message = "<!channel|@channel> {3} is going to {1}, order <{0}|here>! Deadline in {2} minutes!".format( # pylint: disable=C0301
url_for("order_bp.order_from_id", order_id=order_item.id, _external=True), url_for("order_bp.order_from_id", order_id=order_item.id,
_external=True),
order_item.location.name, order_item.location.name,
remaining_minutes(order_item.stoptime), remaining_minutes(order_item.stoptime),
order_item.courrier.username.title(), order_item.courrier.username.title(),
) )
else: else:
message = "<!channel|@channel> New order for {}. Deadline in {} minutes. <{}|Open here.>".format( message = "<!channel|@channel> New order for {}. Deadline in {} minutes. <{}|Open here.>".format( # pylint: disable=C0301
order_item.location.name, order_item.location.name,
remaining_minutes(order_item.stoptime), remaining_minutes(order_item.stoptime),
url_for("order_bp.order_from_id", order_id=order_item.id, _external=True), url_for("order_bp.order_from_id",
order_id=order_item.id, _external=True),
) )
webhookthread = WebhookSenderThread(message, app.config["SLACK_WEBHOOK"]) webhookthread = WebhookSenderThread(message, app.config["SLACK_WEBHOOK"])
webhookthread.start() webhookthread.start()
@ -28,6 +32,7 @@ def post_order_to_webhook(order_item) -> None:
class WebhookSenderThread(Thread): class WebhookSenderThread(Thread):
def __init__(self, message: str, url: str) -> None: def __init__(self, message: str, url: str) -> None:
"Extension of the Thread class, which sends a webhook for the notification"
super(WebhookSenderThread, self).__init__() super(WebhookSenderThread, self).__init__()
self.message = message self.message = message
self.url = url self.url = url
@ -36,6 +41,7 @@ class WebhookSenderThread(Thread):
self.slack_webhook() self.slack_webhook()
def slack_webhook(self) -> None: def slack_webhook(self) -> None:
"The webhook for the specified chat platform"
if self.url: if self.url:
requests.post(url, json={"text": self.message}) requests.post(url, json={"text": self.message})
else: else:
@ -43,6 +49,7 @@ class WebhookSenderThread(Thread):
def remaining_minutes(value) -> str: def remaining_minutes(value) -> str:
"Return the remaining minutes until the deadline of and order"
delta = value - datetime.now() delta = value - datetime.now()
if delta.total_seconds() < 0: if delta.total_seconds() < 0:
return "0" return "0"

View file

@ -1,4 +1,5 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"Script to run Haldis on a server"
import os import os
import sys import sys

View file

@ -1,3 +1,6 @@
"Script which contains several utils for Haldis"
def euro_string(value: int) -> str: def euro_string(value: int) -> str:
""" """
Convert cents to string formatted euro Convert cents to string formatted euro

View file

@ -1,3 +1,4 @@
"Script containing everything specific to ZeusWPI"
import typing import typing
from flask import (Blueprint, current_app, flash, redirect, request, session, from flask import (Blueprint, current_app, flash, redirect, request, session,
@ -12,6 +13,7 @@ oauth_bp = Blueprint("oauth_bp", __name__)
def zeus_login(): def zeus_login():
"Log in using ZeusWPI"
return current_app.zeus.authorize( return current_app.zeus.authorize(
callback=url_for("oauth_bp.authorized", _external=True) callback=url_for("oauth_bp.authorized", _external=True)
) )
@ -21,6 +23,7 @@ def zeus_login():
def authorized() -> typing.Any: def authorized() -> typing.Any:
# type is 'typing.Union[str, Response]', but this errors due to # type is 'typing.Union[str, Response]', but this errors due to
# https://github.com/python/mypy/issues/7187 # https://github.com/python/mypy/issues/7187
"Check authorized status"
resp = current_app.zeus.authorized_response() resp = current_app.zeus.authorized_response()
if resp is None: if resp is None:
return "Access denied: reason=%s error=%s" % ( return "Access denied: reason=%s error=%s" % (
@ -35,9 +38,10 @@ def authorized() -> typing.Any:
username = me.data.get("username", "").lower() username = me.data.get("username", "").lower()
user = User.query.filter_by(username=username).first() 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) return login_and_redirect_user(user)
elif len(username) > 0: elif username > 0:
user = create_user(username) user = create_user(username)
return login_and_redirect_user(user) return login_and_redirect_user(user)
@ -46,6 +50,7 @@ def authorized() -> typing.Any:
def init_oauth(app): def init_oauth(app):
"Initialize the OAuth for ZeusWPI"
oauth = OAuth(app) oauth = OAuth(app)
zeus = oauth.remote_app( zeus = oauth.remote_app(
@ -59,6 +64,7 @@ def init_oauth(app):
authorize_url="https://adams.ugent.be/oauth/oauth2/authorize/", authorize_url="https://adams.ugent.be/oauth/oauth2/authorize/",
) )
# pylint: disable=W0612
@zeus.tokengetter @zeus.tokengetter
def get_zeus_oauth_token(): def get_zeus_oauth_token():
return session.get("zeus_token") return session.get("zeus_token")
@ -67,11 +73,13 @@ def init_oauth(app):
def login_and_redirect_user(user) -> Response: def login_and_redirect_user(user) -> Response:
"Log in the user and then redirect them"
login_user(user) login_user(user)
return redirect(url_for("general_bp.home")) return redirect(url_for("general_bp.home"))
def create_user(username) -> User: def create_user(username) -> User:
"Create a temporary user if it is needed"
user = User() user = User()
user.configure(username, False, 1) user.configure(username, False, 1)
db.session.add(user) db.session.add(user)