51 lines
1.4 KiB
Python
51 lines
1.4 KiB
Python
|
|
import importlib
|
||
|
|
import os
|
||
|
|
|
||
|
|
from flask import Flask
|
||
|
|
from flask_migrate import Migrate
|
||
|
|
from flask_sqlalchemy import SQLAlchemy
|
||
|
|
|
||
|
|
_context = None
|
||
|
|
|
||
|
|
|
||
|
|
class ApplicationContext:
|
||
|
|
"""
|
||
|
|
Interface for the flask application
|
||
|
|
"""
|
||
|
|
|
||
|
|
def __init__(self, schema_module_name: str):
|
||
|
|
self.schema_module = importlib.import_module(schema_module_name)
|
||
|
|
self.db = SQLAlchemy()
|
||
|
|
self.migrate = Migrate()
|
||
|
|
self._app = Flask("flask")
|
||
|
|
|
||
|
|
self._initialized = False
|
||
|
|
self._enable_migrations = False
|
||
|
|
|
||
|
|
self._app.config["SECRET_KEY"] = os.getenv("SECRET_KEY", "secret string")
|
||
|
|
self._app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv(
|
||
|
|
"DATABASE_URL", "sqlite:////" + os.path.join(self._app.root_path, "data.db")
|
||
|
|
)
|
||
|
|
self._app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
|
||
|
|
|
||
|
|
@property
|
||
|
|
def flask(self):
|
||
|
|
if not self._initialized:
|
||
|
|
raise RuntimeError("You must initialize first.")
|
||
|
|
return self._app
|
||
|
|
|
||
|
|
def initialize(self):
|
||
|
|
self.db.init_app(self._app)
|
||
|
|
if self._enable_migrations:
|
||
|
|
self.migrate.init_app(self._app, self.db)
|
||
|
|
self._initialized = True
|
||
|
|
return self.flask
|
||
|
|
|
||
|
|
|
||
|
|
def initialize(schema_module_name: str = "ttfrog.schema"):
|
||
|
|
global _context
|
||
|
|
if not _context:
|
||
|
|
_context = ApplicationContext(schema_module_name)
|
||
|
|
_context.initialize()
|
||
|
|
return _context
|