Move prechecks to run file

Add Verbose option
Cleanup run file
This commit is contained in:
Michał Gdula 2023-03-12 12:29:29 +00:00
parent 800ba38241
commit 2eec988815
8 changed files with 149 additions and 78 deletions

View file

@ -16,28 +16,13 @@ from flask import Flask, render_template
# Configuration
from dotenv import load_dotenv
import platformdirs
import yaml
from yaml import FullLoader, load
from . import theme_manager
from . import setup
# Run setup checks
setup.SetupApp()
USER_DIR = platformdirs.user_config_dir('onlylegs')
# Get environment variables
load_dotenv(os.path.join(USER_DIR, '.env'))
print("Loaded environment variables")
# Get config file
with open(os.path.join(USER_DIR, 'conf.yml'), encoding='utf-8') as f:
conf = yaml.load(f, Loader=yaml.FullLoader)
print("Loaded gallery config")
def create_app(test_config=None):
def create_app(test_config=None, verbose=False):
"""
Create and configure the main app
"""
@ -45,6 +30,17 @@ def create_app(test_config=None):
assets = Environment()
cache = Cache(config={'CACHE_TYPE': 'SimpleCache', 'CACHE_DEFAULT_TIMEOUT': 300})
compress = Compress()
# Get environment variables
load_dotenv(os.path.join(USER_DIR, '.env'))
if verbose:
print("Loaded environment variables")
# Get config file
with open(os.path.join(USER_DIR, 'conf.yml'), encoding='utf-8') as f:
conf = load(f, Loader=FullLoader)
if verbose:
print("Loaded gallery config")
# App configuration
app.config.from_mapping(
@ -67,7 +63,9 @@ def create_app(test_config=None):
pass
# Load theme
theme_manager.CompileTheme('default', app.root_path)
from . import theme_manager
theme_manager.CompileTheme('default', app.root_path, verbose)
# Bundle JS files
js = Bundle('js/*.js', output='gen/packed.js')
assets.register('js_all', js)

View file

@ -5,13 +5,16 @@ import os
import platformdirs
from sqlalchemy import create_engine, Column, Integer, String, Boolean, DateTime, ForeignKey, PickleType
from sqlalchemy.orm import declarative_base, relationship, backref, mapped_column
from sqlalchemy.orm import declarative_base, relationship
USER_DIR = platformdirs.user_config_dir('onlylegs')
DB_PATH = os.path.join(USER_DIR, 'gallery.sqlite')
path_to_db = os.path.join(platformdirs.user_config_dir('onlylegs'), 'gallery.sqlite')
engine = create_engine(f'sqlite:///{path_to_db}', echo=False)
# engine = create_engine('postgresql://username:password@host:port/database_name', echo=False)
# engine = create_engine('mysql://username:password@host:port/database_name', echo=False)
engine = create_engine(f'sqlite:///{DB_PATH}', echo=False)
base = declarative_base()
@ -130,4 +133,6 @@ class Bans (base): # pylint: disable=too-few-public-methods, C0103
created_at = Column(DateTime, nullable=False)
base.metadata.create_all(engine)
# check if database file exists, if not create it
if not os.path.isfile(DB_PATH):
base.metadata.create_all(engine)

View file

@ -1,125 +0,0 @@
"""
OnlyLegs - Setup
Runs when the app detects that there is no user directory
"""
import os
import sys
import platformdirs
import logging
import yaml
USER_DIR = platformdirs.user_config_dir('onlylegs')
class SetupApp:
"""
Setup the application on first run
"""
def __init__(self):
"""
Main setup function
"""
print("Running setup...")
self.requires_restart = False
if not os.path.exists(USER_DIR):
self.make_dir()
if not os.path.exists(os.path.join(USER_DIR, '.env')):
self.make_env()
if not os.path.exists(os.path.join(USER_DIR, 'conf.yml')):
self.make_yaml()
self.logging_config()
if self.requires_restart:
print("WARNING: You need to restart and edit the config files before running the app again!")
print("You can find the config files at:", USER_DIR)
sys.exit()
@staticmethod
def make_dir():
"""
Create the user directory
"""
try:
os.makedirs(USER_DIR)
os.makedirs(os.path.join(USER_DIR, 'instance'))
print("Created user directory at:", USER_DIR)
except Exception as err:
print("Error creating user directory:", err)
sys.exit(1)
@staticmethod
def make_env():
"""
Create the .env file with default values
"""
env_conf = {
'FLASK_SECRET': 'dev',
}
try:
with open(os.path.join(USER_DIR, '.env'), encoding='utf-8', mode='w+') as file:
for key, value in env_conf.items():
file.write(f"{key}={value}\n")
print("Created environment variables")
except Exception as err:
print("Error creating environment variables:", err)
sys.exit(1)
print("Generated default .env file, please edit!")
@staticmethod
def make_yaml():
"""
Create the YAML config file with default values
"""
yaml_conf = {
'admin': {
'name': 'Real Person',
'username': 'User',
'email': 'real-email@some.place'
},
'upload': {
'allowed-extensions': {
'jpg': 'jpeg',
'jpeg': 'jpeg',
'png': 'png',
'webp': 'webp'
},
'max-size': 69,
'rename': 'GWA_\{\{username\}\}_\{\{time\}\}'
},
'website': {
'name': 'OnlyLegs',
'motto': 'Gwa Gwa',
'language': 'english'
}
}
try:
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)
print("Created default gallery config")
except Exception as err:
print("Error creating default gallery config:", err)
sys.exit(1)
print("Generated default YAML config, please edit!")
@staticmethod
def logging_config():
logs_path = os.path.join(platformdirs.user_config_dir('onlylegs'), 'logs')
if not os.path.isdir(logs_path):
os.mkdir(logs_path)
print("Created logs directory at:", logs_path)
logging.getLogger('werkzeug').disabled = True
logging.basicConfig(
filename=os.path.join(logs_path, 'only.log'),
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S',
format='%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s',
encoding='utf-8')

View file

@ -28,7 +28,7 @@
</div>
{% else %}
<div class="big-text">
<h1>No image!</h1>
<h1>No images</h1>
{% if g.user %}
<p>You can get started by uploading an image!</p>
{% else %}

View file

@ -12,13 +12,14 @@ class CompileTheme:
"""
Compiles the theme into the static folder
"""
def __init__(self, theme_name, app_path):
def __init__(self, theme_name, app_path, verbose=False):
"""
Initialize the theme manager
Compiles the theme into the static folder and loads the fonts
"""
print(f"Loading '{theme_name}' theme...")
if verbose:
print(f"Loading '{theme_name}' theme...")
theme_path = os.path.join(app_path, 'themes', theme_name)
theme_dest = os.path.join(app_path, 'static', 'theme')
@ -30,11 +31,11 @@ class CompileTheme:
self.load_sass(theme_path, theme_dest)
self.load_fonts(theme_path, theme_dest)
now = datetime.now()
print(f"{now.hour}:{now.minute}:{now.second} - Done!\n")
if verbose:
print(f"{datetime.now().hour}:{datetime.now().minute}:{datetime.now().second} - Done!\n")
@staticmethod
def load_sass(source_path, css_dest):
def load_sass(source_path, css_dest, verbose=False):
"""
Compile the sass (or scss) file into css and save it to the static folder
"""
@ -56,10 +57,11 @@ class CompileTheme:
print("Failed to compile!\n", err)
sys.exit(1)
print("Compiled successfully!")
if verbose:
print("Compiled successfully!")
@staticmethod
def load_fonts(source_path, font_dest):
def load_fonts(source_path, font_dest, verbose=False):
"""
Copy the fonts folder to the static folder
"""
@ -68,7 +70,6 @@ class CompileTheme:
font_dest = os.path.join(font_dest, 'fonts')
if os.path.exists(font_dest):
print("Updating fonts...")
try:
shutil.rmtree(font_dest)
except Exception as err:
@ -77,7 +78,9 @@ class CompileTheme:
try:
shutil.copytree(source_path, font_dest)
print("Copied new fonts!")
except Exception as err:
print("Failed to copy fonts!\n", err)
sys.exit(1)
if verbose:
print("Fonts copied successfully!")