From 05dc158719366a1a6e0c62b50ee3aefe45bf57ee Mon Sep 17 00:00:00 2001 From: Ferdinand Thiessen Date: Thu, 18 Nov 2021 12:54:37 +0100 Subject: [PATCH] [cleanup] PEP8 cleanup --- flaschengeist/app.py | 3 +- flaschengeist/config.py | 9 +++++- flaschengeist/controller/imageController.py | 18 +++++------ flaschengeist/database.py | 1 + flaschengeist/models/__init__.py | 2 +- flaschengeist/models/image.py | 3 +- flaschengeist/models/user.py | 4 ++- flaschengeist/plugins/__init__.py | 2 +- flaschengeist/plugins/auth_ldap/__init__.py | 16 +++++----- flaschengeist/plugins/auth_plain/__init__.py | 8 ++++- .../plugins/balance/balance_controller.py | 9 +++++- flaschengeist/plugins/events/models.py | 18 +++++++++-- flaschengeist/plugins/pricelist/models.py | 6 +++- .../plugins/pricelist/pricelist_controller.py | 31 ++++++++++++++++--- setup.py | 11 ++++++- tests/conftest.py | 8 ++++- 16 files changed, 115 insertions(+), 34 deletions(-) diff --git a/flaschengeist/app.py b/flaschengeist/app.py index 0012c6f..8d15c11 100644 --- a/flaschengeist/app.py +++ b/flaschengeist/app.py @@ -52,7 +52,8 @@ def __load_plugins(app): app.register_blueprint(plugin.blueprint) except: logger.error( - f"Plugin {entry_point.name} was enabled, but could not be loaded due to an error.", exc_info=True + f"Plugin {entry_point.name} was enabled, but could not be loaded due to an error.", + exc_info=True, ) del plugin continue diff --git a/flaschengeist/config.py b/flaschengeist/config.py index 47af03f..48c71b2 100644 --- a/flaschengeist/config.py +++ b/flaschengeist/config.py @@ -69,7 +69,14 @@ def configure_app(app, test_config=None): read_configuration(test_config) # Always enable this builtin plugins! - update_dict(config, {"auth": {"enabled": True}, "roles": {"enabled": True}, "users": {"enabled": True}}) + update_dict( + config, + { + "auth": {"enabled": True}, + "roles": {"enabled": True}, + "users": {"enabled": True}, + }, + ) if "secret_key" not in config["FLASCHENGEIST"]: logger.warning("No secret key was configured, please configure one for production systems!") diff --git a/flaschengeist/controller/imageController.py b/flaschengeist/controller/imageController.py index 5139d56..26bfd2d 100644 --- a/flaschengeist/controller/imageController.py +++ b/flaschengeist/controller/imageController.py @@ -13,7 +13,7 @@ from flaschengeist.config import config def check_mimetype(mime: str): - return mime in config["FILES"].get('allowed_mimetypes', []) + return mime in config["FILES"].get("allowed_mimetypes", []) def send_image(id: int = None, image: Image = None): @@ -32,10 +32,10 @@ def send_thumbnail(id: int = None, image: Image = None): if not image.thumbnail_: with PImage.open(image.open()) as im: im.thumbnail(tuple(config["FILES"].get("thumbnail_size"))) - s = image.path_.split('.') - s.insert(len(s)-1, 'thumbnail') - im.save('.'.join(s)) - image.thumbnail_ = '.'.join(s) + s = image.path_.split(".") + s.insert(len(s) - 1, "thumbnail") + im.save(".".join(s)) + image.thumbnail_ = ".".join(s) db.session.commit() return send_file(image.thumbnail_, mimetype=image.mimetype_, download_name=image.filename_) @@ -45,10 +45,10 @@ def upload_image(file: FileStorage): raise UnprocessableEntity path = Path(config["FILES"].get("data_path")) / str(date.today().year) - path.mkdir(mode=int('0700', 8), parents=True, exist_ok=True) - - if file.filename.count('.') < 1: - name = secure_filename(file.filename + '.' + file.mimetype.split('/')[-1]) + path.mkdir(mode=int("0700", 8), parents=True, exist_ok=True) + + if file.filename.count(".") < 1: + name = secure_filename(file.filename + "." + file.mimetype.split("/")[-1]) else: name = secure_filename(file.filename) img = Image(mimetype_=file.mimetype, filename_=name) diff --git a/flaschengeist/database.py b/flaschengeist/database.py index 85fc3e1..410e0cf 100644 --- a/flaschengeist/database.py +++ b/flaschengeist/database.py @@ -6,5 +6,6 @@ db = SQLAlchemy() def case_sensitive(s): if db.session.bind.dialect.name == "mysql": from sqlalchemy import func + return func.binary(s) return s diff --git a/flaschengeist/models/__init__.py b/flaschengeist/models/__init__.py index 4eca8e3..acffc1a 100644 --- a/flaschengeist/models/__init__.py +++ b/flaschengeist/models/__init__.py @@ -44,7 +44,7 @@ class ModelSerializeMixin: class Serial(TypeDecorator): """Same as MariaDB Serial used for IDs""" - cache_ok=True + cache_ok = True impl = BigInteger().with_variant(mysql.BIGINT(unsigned=True), "mysql").with_variant(sqlite.INTEGER, "sqlite") diff --git a/flaschengeist/models/image.py b/flaschengeist/models/image.py index 1242c2e..7cf9967 100644 --- a/flaschengeist/models/image.py +++ b/flaschengeist/models/image.py @@ -6,6 +6,7 @@ from pathlib import Path from . import ModelSerializeMixin, Serial from ..database import db + class Image(db.Model, ModelSerializeMixin): __tablename__ = "image" id: int = db.Column("id", Serial, primary_key=True) @@ -18,7 +19,7 @@ class Image(db.Model, ModelSerializeMixin): return open(self.path_, "rb") -@event.listens_for(Image, 'before_delete') +@event.listens_for(Image, "before_delete") def clear_file(mapper, connection, target: Image): if target.path_: p = Path(target.path_) diff --git a/flaschengeist/models/user.py b/flaschengeist/models/user.py index 84116a6..16b901c 100644 --- a/flaschengeist/models/user.py +++ b/flaschengeist/models/user.py @@ -67,7 +67,9 @@ class User(db.Model, ModelSerializeMixin): sessions_ = db.relationship("Session", back_populates="user_") _attributes = db.relationship( - "_UserAttribute", collection_class=attribute_mapped_collection("name"), cascade="all, delete" + "_UserAttribute", + collection_class=attribute_mapped_collection("name"), + cascade="all, delete", ) @property diff --git a/flaschengeist/plugins/__init__.py b/flaschengeist/plugins/__init__.py index fabc4e2..da5bc84 100644 --- a/flaschengeist/plugins/__init__.py +++ b/flaschengeist/plugins/__init__.py @@ -33,7 +33,7 @@ class Plugin: blueprint = None # You have to override permissions = [] # You have to override - id = "dev.flaschengeist.plugin" # You have to override + id = "dev.flaschengeist.plugin" # You have to override name = "plugin" # You have to override models = None # You have to override diff --git a/flaschengeist/plugins/auth_ldap/__init__.py b/flaschengeist/plugins/auth_ldap/__init__.py index 3ceb6e0..846dc5d 100644 --- a/flaschengeist/plugins/auth_ldap/__init__.py +++ b/flaschengeist/plugins/auth_ldap/__init__.py @@ -96,12 +96,14 @@ class AuthLDAP(AuthPlugin): display_name=user.display_name, base_dn=self.base_dn, ) - attributes.update({ - "sn": user.lastname, - "givenName": user.firstname, - "uid": user.userid, - "userPassword": self.__hash(password), - }) + attributes.update( + { + "sn": user.lastname, + "givenName": user.firstname, + "uid": user.userid, + "userPassword": self.__hash(password), + } + ) ldap_conn.add(dn, self.object_classes, attributes) self._set_roles(user) except (LDAPPasswordIsMandatoryError, LDAPBindError): @@ -145,7 +147,7 @@ class AuthLDAP(AuthPlugin): if "jpegPhoto" in r and len(r["jpegPhoto"]) > 0: avatar = _Avatar() avatar.mimetype = "image/jpeg" - avatar.binary = bytearray(r['jpegPhoto'][0]) + avatar.binary = bytearray(r["jpegPhoto"][0]) return avatar else: raise NotFound diff --git a/flaschengeist/plugins/auth_plain/__init__.py b/flaschengeist/plugins/auth_plain/__init__.py index c8de367..3b2b8f7 100644 --- a/flaschengeist/plugins/auth_plain/__init__.py +++ b/flaschengeist/plugins/auth_plain/__init__.py @@ -19,7 +19,13 @@ class AuthPlain(AuthPlugin): if User.query.first() is None: logger.info("Installing admin user") role = Role(name="Superuser", permissions=Permission.query.all()) - admin = User(userid="admin", firstname="Admin", lastname="Admin", mail="", roles_=[role]) + admin = User( + userid="admin", + firstname="Admin", + lastname="Admin", + mail="", + roles_=[role], + ) self.modify_user(admin, None, "admin") db.session.add(admin) db.session.commit() diff --git a/flaschengeist/plugins/balance/balance_controller.py b/flaschengeist/plugins/balance/balance_controller.py index 58b1152..1d6174f 100644 --- a/flaschengeist/plugins/balance/balance_controller.py +++ b/flaschengeist/plugins/balance/balance_controller.py @@ -114,7 +114,14 @@ def get_transaction(transaction_id) -> Transaction: def get_transactions( - user, start=None, end=None, limit=None, offset=None, show_reversal=False, show_cancelled=True, descending=False + user, + start=None, + end=None, + limit=None, + offset=None, + show_reversal=False, + show_cancelled=True, + descending=False, ): count = None query = Transaction.query.filter((Transaction.sender_ == user) | (Transaction.receiver_ == user)) diff --git a/flaschengeist/plugins/events/models.py b/flaschengeist/plugins/events/models.py index daf308a..51fd4a7 100644 --- a/flaschengeist/plugins/events/models.py +++ b/flaschengeist/plugins/events/models.py @@ -39,7 +39,13 @@ class Service(db.Model, ModelSerializeMixin): is_backup: bool = db.Column(db.Boolean, default=False) value: float = db.Column(db.Numeric(precision=3, scale=2, asdecimal=False), nullable=False) - _job_id = db.Column("job_id", Serial, db.ForeignKey(f"{_table_prefix_}job.id"), nullable=False, primary_key=True) + _job_id = db.Column( + "job_id", + Serial, + db.ForeignKey(f"{_table_prefix_}job.id"), + nullable=False, + primary_key=True, + ) _user_id = db.Column("user_id", Serial, db.ForeignKey("user.id"), nullable=False, primary_key=True) user_: User = db.relationship("User") @@ -83,11 +89,17 @@ class Event(db.Model, ModelSerializeMixin): type: Union[EventType, int] = db.relationship("EventType") is_template: bool = db.Column(db.Boolean, default=False) jobs: list[Job] = db.relationship( - "Job", back_populates="event_", cascade="all,delete,delete-orphan", order_by="[Job.start, Job.end]" + "Job", + back_populates="event_", + cascade="all,delete,delete-orphan", + order_by="[Job.start, Job.end]", ) # Protected for internal use _type_id = db.Column( - "type_id", Serial, db.ForeignKey(f"{_table_prefix_}event_type.id", ondelete="CASCADE"), nullable=False + "type_id", + Serial, + db.ForeignKey(f"{_table_prefix_}event_type.id", ondelete="CASCADE"), + nullable=False, ) diff --git a/flaschengeist/plugins/pricelist/models.py b/flaschengeist/plugins/pricelist/models.py index 55b1152..630766d 100644 --- a/flaschengeist/plugins/pricelist/models.py +++ b/flaschengeist/plugins/pricelist/models.py @@ -132,7 +132,11 @@ class DrinkPriceVolume(db.Model, ModelSerializeMixin): _prices: list[DrinkPrice] = db.relationship( DrinkPrice, back_populates="_volume", cascade="all,delete,delete-orphan" ) - ingredients: list[Ingredient] = db.relationship("Ingredient", foreign_keys=Ingredient.volume_id, cascade="all,delete,delete-orphan") + ingredients: list[Ingredient] = db.relationship( + "Ingredient", + foreign_keys=Ingredient.volume_id, + cascade="all,delete,delete-orphan", + ) def __repr__(self): return f"DrinkPriceVolume({self.id},{self.drink_id},{self.volume},{self.prices})" diff --git a/flaschengeist/plugins/pricelist/pricelist_controller.py b/flaschengeist/plugins/pricelist/pricelist_controller.py index d42085a..bd89518 100644 --- a/flaschengeist/plugins/pricelist/pricelist_controller.py +++ b/flaschengeist/plugins/pricelist/pricelist_controller.py @@ -5,11 +5,21 @@ from flaschengeist import logger from flaschengeist.database import db from flaschengeist.utils.decorators import extract_session -from .models import Drink, DrinkPrice, Ingredient, Tag, DrinkType, DrinkPriceVolume, DrinkIngredient, ExtraIngredient +from .models import ( + Drink, + DrinkPrice, + Ingredient, + Tag, + DrinkType, + DrinkPriceVolume, + DrinkIngredient, + ExtraIngredient, +) from .permissions import EDIT_VOLUME, EDIT_PRICE, EDIT_INGREDIENTS_DRINK import flaschengeist.controller.imageController as image_controller + def update(): db.session.commit() @@ -130,7 +140,14 @@ def _create_public_drink(drink): def get_drinks( - name=None, public=False, limit=None, offset=None, search_name=None, search_key=None, ingredient=False, receipt=None + name=None, + public=False, + limit=None, + offset=None, + search_name=None, + search_key=None, + ingredient=False, + receipt=None, ): count = None if name: @@ -176,7 +193,13 @@ def get_drinks( def get_pricelist( - public=False, limit=None, offset=None, search_name=None, search_key=None, sortBy=None, descending=False + public=False, + limit=None, + offset=None, + search_name=None, + search_key=None, + sortBy=None, + descending=False, ): count = None query = DrinkPrice.query @@ -300,7 +323,7 @@ def update_drink(identifier, data): else: drink = get_drink(identifier) for key, value in data.items(): - if hasattr(drink, key) and key != 'has_image': + if hasattr(drink, key) and key != "has_image": setattr(drink, key, value if value != "" else None) if drink_type: diff --git a/setup.py b/setup.py index d8ccc0f..6d80097 100644 --- a/setup.py +++ b/setup.py @@ -20,7 +20,16 @@ class DocsCommand(Command): def run(self): """Run command.""" - command = ["python", "-m", "pdoc", "--skip-errors", "--html", "--output-dir", self.output, "flaschengeist"] + command = [ + "python", + "-m", + "pdoc", + "--skip-errors", + "--html", + "--output-dir", + self.output, + "flaschengeist", + ] self.announce( "Running command: %s" % str(command), ) diff --git a/tests/conftest.py b/tests/conftest.py index b99d8d6..5290fd8 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -22,7 +22,13 @@ with open(os.path.join(os.path.dirname(__file__), "data.sql"), "r") as f: @pytest.fixture def app(): db_fd, db_path = tempfile.mkstemp() - app = create_app({"TESTING": True, "DATABASE": {"file_path": f"/{db_path}"}, "LOGGING": {"level": "DEBUG"}}) + app = create_app( + { + "TESTING": True, + "DATABASE": {"file_path": f"/{db_path}"}, + "LOGGING": {"level": "DEBUG"}, + } + ) with app.app_context(): install_all() engine = database.db.engine