Skip to content Skip to sidebar Skip to footer

Configure Python Flask App To Use "create_app" Factory And Use Database In Model Class

I'm having trouble getting my app to start when using a create_app() function. I'm new to building apps to this way and from all of my research it seems that my approach is differe

Solution 1:

I've started migrating toward using the form of the create_app pattern that Miguel Grinberg introduces in part XV of his Flask Mega-Tutorial.

In your case, the reference to your db object locked in a local variable inside of create_app. The trick is to get it visible. Consider this scheme, which I use with SQLAlchemy, and which you would adapt to use your wrapper:

main.py
config.py
tests.py
app/
    __init__.py

First, the default configuration which looks something like this (trimmed for brevity)

# config.py
...
classConfig:
    TESTING = False
    SQLALCHEMY_DATABASE_URI = ...
    ...

The config will be used as a default by the factory.

# app/__init__.py
...
db = SQLAlchemy()  # done here so that db is importable
migrate = Migrate()

defcreate_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)
    db.init_app(app)
    migrate.init_app(app, db)
    ... register blueprints, configure logging etc.
    return app

Note that from app import db works.

# main.pyfrom app import create_app
app = create_app()

And thenFLASK_APP=main.py venv/bin/flask run.

And for testing, a subclass of Config uses an in-memory database (and makes other tweaks to avoid hitting external services).

# tests.py
...
classTestConfig(Config):
    TESTING = True
    SQLALCHEMY_DATABASE_URI = 'sqlite://'classExampleTests(unittest.TestCase):
    defsetUp(self):
        self.app = create_app(TestConfig)
        # See Grinberg's tutorial for the other essential bits

Post a Comment for "Configure Python Flask App To Use "create_app" Factory And Use Database In Model Class"