-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp_factory.py
61 lines (48 loc) · 1.88 KB
/
app_factory.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from importlib import import_module
import sys_vars
from alembic import command
from alembic.config import Config
from flask import Flask
from flask_cors import CORS
from flask_smorest import Api
from src.blueprints import all_blueprints, route_embed
from src.core import logger
from src.core.database.schema import db
def create_app() -> Flask:
"""Instance the app."""
# Create the app and enable CORS support
app = Flask(__name__)
CORS(app)
# Put the app secret key into the expected key
app.config["SECRET_KEY"] = sys_vars.get("SECRET_KEY")
app.config.update(sys_vars.get_json("api.json"))
# Don't enable API docs in prod
if sys_vars.get("FLASK_ENV") == "production":
app.config["OPENAPI_URL_PREFIX"] = None
# Enable Discord webhook event logging, falling back to a text log
if sys_vars.get_bool("ENABLE_DISCORD_LOGGING"):
logger.logger.addHandler(logger.DiscordHandler())
else:
logger.logger.addHandler(logger.file_handler("error-linkrot.log", linkrot=True))
# Register the API endpoints
api = Api(app)
for bp in all_blueprints:
import_module(bp.import_name)
api.register_blueprint(bp)
# Register the embed endpoint
import_module(route_embed.import_name)
app.register_blueprint(route_embed)
# Create a database connection
db_path = sys_vars.get_path("DB_PATH").resolve()
with app.app_context():
app.config["SQLALCHEMY_DATABASE_URI"] = f"sqlite:///{db_path.as_posix()}"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.init_app(app)
# Create the database if needed
if not db_path.exists():
db.create_all()
# Tell Alembic this is a new database and we don't need
# to update it to a newer schema
alembic_cfg = Config("alembic.ini")
command.stamp(alembic_cfg, "head")
return app