|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import typing as t |
| 4 | + |
| 5 | +import sqlalchemy as sa |
| 6 | +from flask import Flask |
| 7 | +from flask_alembic import Alembic |
| 8 | +from sqlalchemy import orm |
| 9 | + |
| 10 | +from flask_sqlalchemy_lite import SQLAlchemy |
| 11 | + |
| 12 | + |
| 13 | +class Model(orm.DeclarativeBase): |
| 14 | + metadata: t.ClassVar[sa.MetaData] = sa.MetaData( |
| 15 | + naming_convention={ |
| 16 | + "ix": "ix_%(column_0_label)s", |
| 17 | + "uq": "uq_%(table_name)s_%(column_0_name)s", |
| 18 | + "ck": "ck_%(table_name)s_%(constraint_name)s", |
| 19 | + "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", |
| 20 | + "pk": "pk_%(table_name)s", |
| 21 | + } |
| 22 | + ) |
| 23 | + |
| 24 | + |
| 25 | +db: SQLAlchemy = SQLAlchemy() |
| 26 | +alembic: Alembic = Alembic(metadatas=Model.metadata) |
| 27 | + |
| 28 | + |
| 29 | +def create_app(test_config: dict[str, t.Any] | None = None) -> Flask: |
| 30 | + """Create and configure an instance of the Flask application.""" |
| 31 | + app = Flask(__name__) |
| 32 | + app.config |= { |
| 33 | + # a default secret that should be overridden by instance config |
| 34 | + "SECRET_KEY": "dev", |
| 35 | + # store the database in the instance folder |
| 36 | + "SQLALCHEMY_ENGINES": {"default": "sqlite:///blog.sqlite"}, |
| 37 | + } |
| 38 | + |
| 39 | + if test_config is None: # pragma: no cover |
| 40 | + # load config from env vars when not testing |
| 41 | + app.config.from_prefixed_env() |
| 42 | + else: |
| 43 | + # load the test config if passed in |
| 44 | + app.testing = True |
| 45 | + app.config |= test_config |
| 46 | + |
| 47 | + # apply the extensions to the app |
| 48 | + db.init_app(app) |
| 49 | + alembic.init_app(app) |
| 50 | + |
| 51 | + # apply the blueprints to the app |
| 52 | + from flaskr import auth |
| 53 | + from flaskr import blog |
| 54 | + |
| 55 | + app.register_blueprint(auth.bp) |
| 56 | + app.register_blueprint(blog.bp) |
| 57 | + |
| 58 | + # make url_for('index') == url_for('blog.index') |
| 59 | + # in another app, you might define a separate main index here with |
| 60 | + # app.route, while giving the blog blueprint a url_prefix, but for |
| 61 | + # the tutorial the blog will be the main index |
| 62 | + app.add_url_rule("/", endpoint="index") |
| 63 | + |
| 64 | + return app |
0 commit comments