Bendover for PyLint

This commit is contained in:
Michał Gdula 2023-03-20 17:19:42 +00:00
parent e784ca3011
commit b426a6f6c4
8 changed files with 65 additions and 48 deletions

View file

@ -13,12 +13,13 @@ from flask_caching import Cache
from flask_assets import Environment, Bundle from flask_assets import Environment, Bundle
from flask import Flask, render_template from flask import Flask, render_template
from gallery.utils import theme_manager
# Configuration # Configuration
from dotenv import load_dotenv
import platformdirs import platformdirs
from yaml import FullLoader, load from dotenv import load_dotenv
from yaml import FullLoader, safe_load
# Utils
from gallery.utils import theme_manager
USER_DIR = platformdirs.user_config_dir('onlylegs') USER_DIR = platformdirs.user_config_dir('onlylegs')
@ -32,14 +33,14 @@ def create_app(test_config=None):
assets = Environment() assets = Environment()
cache = Cache(config={'CACHE_TYPE': 'SimpleCache', 'CACHE_DEFAULT_TIMEOUT': 300}) cache = Cache(config={'CACHE_TYPE': 'SimpleCache', 'CACHE_DEFAULT_TIMEOUT': 300})
compress = Compress() compress = Compress()
# Get environment variables # Get environment variables
load_dotenv(os.path.join(USER_DIR, '.env')) load_dotenv(os.path.join(USER_DIR, '.env'))
print("Loaded environment variables") print("Loaded environment variables")
# Get config file # Get config file
with open(os.path.join(USER_DIR, 'conf.yml'), encoding='utf-8') as f: with open(os.path.join(USER_DIR, 'conf.yml'), encoding='utf-8') as file:
conf = load(f, Loader=FullLoader) conf = safe_load(file, loader=FullLoader)
print("Loaded gallery config") print("Loaded gallery config")
# App configuration # App configuration
@ -64,10 +65,10 @@ def create_app(test_config=None):
# Load theme # Load theme
theme_manager.CompileTheme('default', app.root_path) theme_manager.CompileTheme('default', app.root_path)
# Bundle JS files # Bundle JS files
js = Bundle('js/*.js', output='gen/packed.js') js_scripts = Bundle('js/*.js', output='gen/packed.js')
assets.register('js_all', js) assets.register('js_all', js_scripts)
# Error handlers # Error handlers
@app.errorhandler(403) @app.errorhandler(403)

View file

@ -4,7 +4,8 @@ OnlyLegs - Database models and functions for SQLAlchemy
import os import os
import platformdirs import platformdirs
from sqlalchemy import create_engine, Column, Integer, String, Boolean, DateTime, ForeignKey, PickleType from sqlalchemy import (
create_engine, Column, Integer, String, Boolean, DateTime, ForeignKey, PickleType)
from sqlalchemy.orm import declarative_base, relationship from sqlalchemy.orm import declarative_base, relationship
@ -47,18 +48,18 @@ class Posts (base): # pylint: disable=too-few-public-methods, C0103
id = Column(Integer, primary_key=True) id = Column(Integer, primary_key=True)
author_id = Column(Integer, ForeignKey('users.id')) author_id = Column(Integer, ForeignKey('users.id'))
created_at = Column(DateTime, nullable=False) created_at = Column(DateTime, nullable=False)
file_name = Column(String, unique=True, nullable=False) file_name = Column(String, unique=True, nullable=False)
file_type = Column(String, nullable=False) file_type = Column(String, nullable=False)
image_exif = Column(PickleType, nullable=False) image_exif = Column(PickleType, nullable=False)
image_colours = Column(PickleType, nullable=False) image_colours = Column(PickleType, nullable=False)
post_description = Column(String, nullable=False) post_description = Column(String, nullable=False)
post_alt = Column(String, nullable=False) post_alt = Column(String, nullable=False)
junction = relationship('GroupJunction', backref='posts') junction = relationship('GroupJunction', backref='posts')
class Thumbnails (base): # pylint: disable=too-few-public-methods, C0103 class Thumbnails (base): # pylint: disable=too-few-public-methods, C0103
""" """
@ -148,4 +149,4 @@ class Bans (base): # pylint: disable=too-few-public-methods, C0103
# check if database file exists, if not create it # check if database file exists, if not create it
if not os.path.isfile(DB_PATH): if not os.path.isfile(DB_PATH):
base.metadata.create_all(engine) base.metadata.create_all(engine)
print('Database created') print('Database created')

View file

@ -65,7 +65,7 @@ class Metadata:
'Software': {}, 'Software': {},
'File': {}, 'File': {},
} }
# Thanks chatGPT xP # Thanks chatGPT xP
for key, value in encoded_exif.items(): for key, value in encoded_exif.items():
for mapping_name, mapping_val in EXIF_MAPPING: for mapping_name, mapping_val in EXIF_MAPPING:

View file

@ -279,7 +279,7 @@ def lens_specification(value):
""" """
try: try:
return str(value[0] / value[1]) + 'mm - ' + str(value[2] / value[3]) + 'mm' return str(value[0] / value[1]) + 'mm - ' + str(value[2] / value[3]) + 'mm'
except Exception as err: except Exception:
return None return None

View file

@ -26,7 +26,7 @@ class CompileTheme:
if not os.path.exists(theme_path): if not os.path.exists(theme_path):
print("Theme does not exist!") print("Theme does not exist!")
sys.exit(1) sys.exit(1)
if not os.path.exists(theme_dest): if not os.path.exists(theme_dest):
os.makedirs(theme_dest) os.makedirs(theme_dest)

17
run.py
View file

@ -1,3 +1,10 @@
"""
Run script for OnlyLegs
"""
from setup.args import PORT, ADDRESS, WORKERS, DEBUG
from setup.configuration import Configuration
print(""" print("""
___ _ _ ___ _ _
/ _ \ _ __ | |_ _| | ___ __ _ ___ / _ \ _ __ | |_ _| | ___ __ _ ___
@ -9,10 +16,6 @@ Created by Fluffy Bean - Version 23.03.20
""") """)
from setup.args import PORT, ADDRESS, WORKERS, DEBUG
from setup.configuration import Configuration
Configuration() # Run pre-checks Configuration() # Run pre-checks
@ -25,15 +28,15 @@ if DEBUG:
create_app().run(host=ADDRESS, port=PORT, debug=True, threaded=True) create_app().run(host=ADDRESS, port=PORT, debug=True, threaded=True)
else: else:
from setup.runner import OnlyLegs from setup.runner import OnlyLegs # pylint: disable=C0412
# If no address is specified, bind the server to all interfaces # If no address is specified, bind the server to all interfaces
if not ADDRESS: if not ADDRESS:
ADDRESS = '0.0.0.0' ADDRESS = '0.0.0.0'
options = { options = {
'bind': f'{ADDRESS}:{PORT}', 'bind': f'{ADDRESS}:{PORT}',
'workers': WORKERS, 'workers': WORKERS,
} }
OnlyLegs(options).run() OnlyLegs(options).run()

View file

@ -4,10 +4,10 @@ Runs when the app detects that there is no user directory
""" """
import os import os
import sys import sys
import platformdirs
import logging import logging
import yaml
import re import re
import platformdirs
import yaml
USER_DIR = platformdirs.user_config_dir('onlylegs') USER_DIR = platformdirs.user_config_dir('onlylegs')
@ -22,19 +22,19 @@ class Configuration:
Main setup function Main setup function
""" """
print("Running startup checks...") print("Running startup checks...")
# Check if the user directory exists # Check if the user directory exists
if not os.path.exists(USER_DIR): if not os.path.exists(USER_DIR):
self.make_dir() self.make_dir()
# Check if the .env file exists # Check if the .env file exists
if not os.path.exists(os.path.join(USER_DIR, '.env')): if not os.path.exists(os.path.join(USER_DIR, '.env')):
self.make_env() self.make_env()
# Check if the conf.yml file exists # Check if the conf.yml file exists
if not os.path.exists(os.path.join(USER_DIR, 'conf.yml')): if not os.path.exists(os.path.join(USER_DIR, 'conf.yml')):
self.make_yaml() self.make_yaml()
# Load the config files # Load the config files
self.logging_config() self.logging_config()
@ -50,7 +50,7 @@ class Configuration:
except Exception as err: except Exception as err:
print("Error creating user directory:", err) print("Error creating user directory:", err)
sys.exit(1) sys.exit(1)
print("Created user directory at:", USER_DIR) print("Created user directory at:", USER_DIR)
@staticmethod @staticmethod
@ -61,7 +61,7 @@ class Configuration:
env_conf = { env_conf = {
'FLASK_SECRET': os.urandom(32).hex(), 'FLASK_SECRET': os.urandom(32).hex(),
} }
try: try:
with open(os.path.join(USER_DIR, '.env'), encoding='utf-8', mode='w+') as file: with open(os.path.join(USER_DIR, '.env'), encoding='utf-8', mode='w+') as file:
for key, value in env_conf.items(): for key, value in env_conf.items():
@ -69,7 +69,7 @@ class Configuration:
except Exception as err: except Exception as err:
print("Error creating environment variables:", err) print("Error creating environment variables:", err)
sys.exit(1) sys.exit(1)
print(""" print("""
#################################################### ####################################################
# A NEW KEY WAS GENERATED FOR YOU! PLEASE NOTE # # A NEW KEY WAS GENERATED FOR YOU! PLEASE NOTE #
@ -87,7 +87,7 @@ class Configuration:
is_correct = False is_correct = False
email_regex = re.compile(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b') email_regex = re.compile(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b')
username_regex = re.compile(r'\b[A-Za-z0-9._%+-]+\b') username_regex = re.compile(r'\b[A-Za-z0-9._%+-]+\b')
print("\nNo config file found, please enter the following information:") print("\nNo config file found, please enter the following information:")
while not is_correct: while not is_correct:
username = input("Admin username: ") username = input("Admin username: ")
@ -98,7 +98,7 @@ class Configuration:
if not username or not username_regex.match(username): if not username or not username_regex.match(username):
print("Username is invalid!") print("Username is invalid!")
continue continue
if not name: if not name:
print("Name is invalid!") print("Name is invalid!")
continue continue
@ -106,11 +106,11 @@ class Configuration:
if not email or not email_regex.match(email): if not email or not email_regex.match(email):
print("Email is invalid!") print("Email is invalid!")
continue continue
# Check if user is happy with the values # Check if user is happy with the values
if input("Is this correct? (y/n): ").lower() == 'y': if input("Is this correct? (y/n): ").lower() == 'y':
is_correct = True is_correct = True
yaml_conf = { yaml_conf = {
'admin': { 'admin': {
'name': name, 'name': name,
@ -133,7 +133,7 @@ class Configuration:
'language': 'en', 'language': 'en',
} }
} }
try: try:
with open(os.path.join(USER_DIR, 'conf.yml'), encoding='utf-8', mode='w+') as file: with open(os.path.join(USER_DIR, 'conf.yml'), encoding='utf-8', mode='w+') as file:
yaml.dump(yaml_conf, file, default_flow_style=False) yaml.dump(yaml_conf, file, default_flow_style=False)
@ -145,6 +145,9 @@ class Configuration:
@staticmethod @staticmethod
def logging_config(): def logging_config():
"""
Set the logging config
"""
logs_path = os.path.join(platformdirs.user_config_dir('onlylegs'), 'logs') logs_path = os.path.join(platformdirs.user_config_dir('onlylegs'), 'logs')
if not os.path.isdir(logs_path): if not os.path.isdir(logs_path):

View file

@ -1,23 +1,32 @@
"""
Gunicorn configuration file
"""
from gunicorn.app.base import Application from gunicorn.app.base import Application
from gunicorn import util from gunicorn import util
class OnlyLegs(Application): class OnlyLegs(Application):
def __init__(self, options={}): """
Gunicorn application
"""
def __init__(self, options={}): # pylint: disable=W0102, W0231
self.usage = None self.usage = None
self.callable = None self.callable = None
self.options = options self.options = options
self.do_load_config() self.do_load_config()
def init(self, *args): def init(self, *args):
"""
Initialize the application
"""
cfg = {} cfg = {}
for k, v in self.options.items(): for setting, value in self.options.items():
if k.lower() in self.cfg.settings and v is not None: if setting.lower() in self.cfg.settings and value is not None:
cfg[k.lower()] = v cfg[setting.lower()] = value
return cfg return cfg
def prog(self): def prog(self): # pylint: disable=C0116, E0202
return 'OnlyLegs' return 'OnlyLegs'
def load(self): def load(self):
return util.import_app('gallery:create_app()') return util.import_app('gallery:create_app()')