This commit is contained in:
Tim Van Baak 2021-06-13 16:31:37 -07:00
parent f9e139d8f9
commit 874c77f5f7
5 changed files with 92 additions and 61 deletions

View File

@ -1,23 +1,23 @@
# Module imports import argparse
from .dict import AttrOrderedDict, ReadOnlyOrderedDict from typing import Optional
from .directory import ( import os
RootConfigDirectoryContext,
UserConfigDirectoryContext,
LexiconConfigDirectoryContext,
is_guid)
# Environment variable name constants
ENV_SECRET_KEY = "AMANUENSIS_SECRET_KEY"
ENV_CONFIG_DIR = "AMANUENSIS_CONFIG_DIR"
ENV_LOG_FILE = "AMANUENSIS_LOG_FILE"
ENV_LOG_FILE_SIZE = "AMANUENSIS_LOG_FILE_SIZE"
ENV_LOG_FILE_NUM = "AMANUENSIS_LOG_FILE_NUM"
__all__ = [ class AmanuensisConfig:
AttrOrderedDict.__name__, """Base config type. Defines config keys for subclasses to override."""
ReadOnlyOrderedDict.__name__, # If AMANUENSIS_CONFIG is defined, the config file it points to may override
RootConfigDirectoryContext.__name__, # config values defined on the config object itself.
UserConfigDirectoryContext.__name__, AMANUENSIS_CONFIG: Optional[str] = None
LexiconConfigDirectoryContext.__name__, STATIC_ROOT: Optional[str] = "static"
is_guid.__name__, SECRET_KEY: Optional[str] = None
] DATABASE_URI: Optional[str] = None
TESTING = False
class EnvironmentConfig(AmanuensisConfig):
"""Loads config values from environment variables."""
AMANUENSIS_CONFIG = os.environ.get("AMANUENSIS_CONFIG", AmanuensisConfig.AMANUENSIS_CONFIG)
STATIC_ROOT = os.environ.get("AMANUENSIS_STATIC_ROOT", AmanuensisConfig.STATIC_ROOT)
# def get_cli_config():

View File

@ -3,8 +3,12 @@ Database connection setup
""" """
from sqlalchemy import create_engine, MetaData, event from sqlalchemy import create_engine, MetaData, event
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.orm import sessionmaker
try:
from greenlet import getcurrent as get_ident
except ImportError:
from threading import get_ident
# Define naming conventions for generated constraints # Define naming conventions for generated constraints
@ -34,7 +38,7 @@ class DbContext:
cursor.close() cursor.close()
# Create a thread-safe session factory # Create a thread-safe session factory
self.session = scoped_session(sessionmaker(bind=self.engine)) self.session = scoped_session(sessionmaker(bind=self.engine), scopefunc=get_ident)
def __call__(self, *args, **kwargs): def __call__(self, *args, **kwargs):
"""Provides shortcut access to session.execute.""" """Provides shortcut access to session.execute."""

View File

@ -435,6 +435,9 @@ class IndexType(enum.Enum):
PREFIX = 2 PREFIX = 2
ETC = 3 ETC = 3
def __str__(self) -> str:
return str(self.name).lower()
class ArticleIndex(ModelBase): class ArticleIndex(ModelBase):
""" """

View File

@ -1,46 +1,67 @@
import os from datetime import datetime
import json
from flask import Flask from flask import Flask, g
from amanuensis.config import RootConfigDirectoryContext, ENV_CONFIG_DIR from amanuensis.config import AmanuensisConfig, EnvironmentConfig
from amanuensis.models import ModelFactory from amanuensis.db import DbContext
from .auth import get_login_manager, bp_auth # from amanuensis.models import ModelFactory
from .helpers import register_custom_filters # from .auth import get_login_manager, bp_auth
from .home import bp_home # from .helpers import register_custom_filters
from .lexicon import bp_lexicon # from .home import bp_home
from .session import bp_session # from .lexicon import bp_lexicon
# from .session import bp_session
def get_app(root: RootConfigDirectoryContext) -> Flask: def get_app(config: AmanuensisConfig) -> Flask:
# Flask app init """Application factory"""
with root.read_config() as cfg: # Create the Flask object
app = Flask( app = Flask(__name__, template_folder=".", static_folder=config.STATIC_ROOT)
__name__,
template_folder='.', # Load keys from the config object
static_folder=cfg.static_root app.config.from_object(config)
)
app.secret_key = bytes.fromhex(cfg.secret_key) # If a config file is now specified, also load keys from there
app.config['root'] = root if app.config.get("AMANUENSIS_CONFIG", None):
app.config['model_factory'] = ModelFactory(root) app.config.from_file(app.config["AMANUENSIS_CONFIG"], json.load)
app.jinja_options['trim_blocks'] = True
app.jinja_options['lstrip_blocks'] = True # Assert that all required config values are now set
register_custom_filters(app) for config_key in ("SECRET_KEY", "DATABASE_URI"):
if not app.config.get(config_key):
raise Exception(f"{config_key} must be defined")
# Create the database context
db = DbContext(app.config["DATABASE_URI"])
# Make the database connection available to requests via g
def db_setup():
g.db = db
app.before_request(db_setup)
# Tear down the session on request teardown
def db_teardown(response_or_exc):
db.session.remove()
app.teardown_appcontext(db_teardown)
# Configure jinja options
app.jinja_options.update(trim_blocks=True, lstrip_blocks=True)
# Flask-Login init # Flask-Login init
login_manager = get_login_manager(root) # login_manager = get_login_manager(root)
login_manager.init_app(app) # login_manager.init_app(app)
# Blueprint inits # Blueprint inits
app.register_blueprint(bp_auth) # app.register_blueprint(bp_auth)
app.register_blueprint(bp_home) # app.register_blueprint(bp_home)
app.register_blueprint(bp_lexicon) # app.register_blueprint(bp_lexicon)
app.register_blueprint(bp_session) # app.register_blueprint(bp_session)
return app return app
def default(): # def wsgi() -> Flask:
cwd = os.getcwd() # return get_app(EnvironmentConfig())
config_dir = os.environ.get(ENV_CONFIG_DIR, "amanuensis")
root = RootConfigDirectoryContext(os.path.join(cwd, config_dir))
return get_app(root) # def run():
# wsgi().run()

View File

@ -16,6 +16,9 @@ pytest = "^5.2"
black = "^21.5b2" black = "^21.5b2"
mypy = "^0.812" mypy = "^0.812"
[tool.poetry.scripts]
amanuensis-server = "amanuensis.server:run"
[tool.black] [tool.black]
extend-exclude = "^/amanuensis/cli/.*|^/amanuensis/config/.*|^/amanuensis/lexicon/.*|^/amanuensis/log/.*|^/amanuensis/models/.*|^/amanuensis/resources/.*|^/amanuensis/server/.*|^/amanuensis/user/.*|^/amanuensis/__main__.py" extend-exclude = "^/amanuensis/cli/.*|^/amanuensis/config/.*|^/amanuensis/lexicon/.*|^/amanuensis/log/.*|^/amanuensis/models/.*|^/amanuensis/resources/.*|^/amanuensis/server/.*|^/amanuensis/user/.*|^/amanuensis/__main__.py"