[cleanup] PEP8 cleanup

This commit is contained in:
Ferdinand Thiessen 2021-11-18 12:54:37 +01:00
parent 92183a4235
commit 05dc158719
16 changed files with 115 additions and 34 deletions

View File

@ -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

View File

@ -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!")

View File

@ -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)

View File

@ -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

View File

@ -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")

View File

@ -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_)

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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()

View File

@ -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))

View File

@ -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,
)

View File

@ -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})"

View File

@ -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:

View File

@ -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),
)

View File

@ -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