└── main.py /main.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from alembic import context 3 | from flask import Flask 4 | from flask_sqlalchemy import SQLAlchemy 5 | from sqlalchemy import create_engine 6 | 7 | logger = logging.getLogger("alembic.env") 8 | 9 | class DatabaseMigration: 10 | """Custom extension to handle Alembic migrations.""" 11 | 12 | def __init__(self, app: Flask, db: SQLAlchemy): 13 | self.app = app 14 | self.db = db 15 | 16 | def get_engine(self): 17 | """Returns the database engine.""" 18 | return create_engine(self.app.config["SQLALCHEMY_DATABASE_URI"]) 19 | 20 | def migrate(self): 21 | """Runs migrations.""" 22 | with self.get_engine().connect() as connection: 23 | context.configure(connection=connection, target_metadata=self.db.metadata) 24 | with context.begin_transaction(): 25 | context.run_migrations() 26 | 27 | 28 | app = Flask(__name__) 29 | app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///example.db" 30 | db = SQLAlchemy(app) 31 | migrator = DatabaseMigration(app, db) 32 | 33 | 34 | @app.cli.command("migrate") 35 | def migrate_command(): 36 | """Runs migrations via Flask CLI.""" 37 | migrator.migrate() 38 | print("Migration completed.") 39 | 40 | 41 | if __name__ == "__main__": 42 | app.run() 43 | --------------------------------------------------------------------------------