Add SQLAlchemy and database boilerplate code
This commit is contained in:
parent
2da6e43797
commit
31df889dcb
15 changed files with 454 additions and 60 deletions
|
|
@ -5,28 +5,58 @@ from flask import Flask
|
|||
|
||||
from tofu_api.api import TofuApiBlueprint
|
||||
from tofu_api.config import DefaultConfig
|
||||
from tofu_api.dependencies import Dependencies
|
||||
|
||||
|
||||
class App(Flask):
|
||||
"""
|
||||
Flask application for Tofu API.
|
||||
"""
|
||||
# Dependencies container
|
||||
dependencies: Dependencies
|
||||
|
||||
def __init__(self):
|
||||
# Set instance path to the project root directory
|
||||
project_root_dir = os.path.abspath('.')
|
||||
|
||||
# Create and configure the app
|
||||
super().__init__(
|
||||
'tofu_api',
|
||||
instance_path=project_root_dir,
|
||||
instance_relative_config=True,
|
||||
)
|
||||
self.config.from_object(DefaultConfig)
|
||||
|
||||
# Load app configuration from YAML file
|
||||
self.config.from_file(os.getenv('FLASK_CONFIG_FILE', default='config.yml'), load=yaml.safe_load)
|
||||
|
||||
# Initialize DI container
|
||||
self.dependencies = Dependencies()
|
||||
|
||||
# Initialize dependencies
|
||||
self.init_database()
|
||||
|
||||
# Register blueprints
|
||||
self.register_blueprint(TofuApiBlueprint(self))
|
||||
|
||||
def init_database(self) -> None:
|
||||
"""
|
||||
Initialize database connection and models.
|
||||
"""
|
||||
# Initialize SQLAlchemy, create the database engine based on the app config
|
||||
db = self.dependencies.get_sqlalchemy()
|
||||
db.init_database(self)
|
||||
|
||||
# Import models to fill the metadata object
|
||||
import tofu_api.models # noqa (unused import)
|
||||
|
||||
# Create all tables
|
||||
# TODO: Use migrations instead
|
||||
db.create_all_tables()
|
||||
|
||||
|
||||
def create_app() -> Flask:
|
||||
"""
|
||||
App factory, returns a Flask app object.
|
||||
"""
|
||||
# Set instance path to the project root directory
|
||||
project_root_dir = os.path.abspath('.')
|
||||
|
||||
# Create and configure the app
|
||||
app = Flask(
|
||||
'tofu_api',
|
||||
instance_path=project_root_dir,
|
||||
instance_relative_config=True,
|
||||
)
|
||||
app.config.from_object(DefaultConfig)
|
||||
|
||||
# Load app configuration from YAML file
|
||||
app.config.from_file(os.getenv('FLASK_CONFIG_FILE', default='config.yml'), load=yaml.safe_load)
|
||||
|
||||
# Register blueprints
|
||||
app.register_blueprint(TofuApiBlueprint())
|
||||
|
||||
# Return WSGI app
|
||||
return app
|
||||
return App()
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue