I want to structure my Flask app something like:
./site.py
./apps/members/__init__.py
./apps/members/models.py
apps.members is a Flask Blueprint.
Now, in order to create the model classes I need to have a hold of the app, something like:
# apps.members.models
from flask import current_app
from flaskext.sqlalchemy import SQLAlchemy
db = SQLAlchemy(current_app)
class Member(db.Model):
# fields here
pass
But if I try and import that model into my Blueprint app, I get the dreaded RuntimeError: working outside of request context. How can I get a hold of my app correctly here? Relative imports might work but they’re pretty ugly and have their own context issues, e.g:
from ...site import app
# ValueError: Attempted relative import beyond toplevel package
The
flask_sqlalchemymodule does not have to be initialized with the app right away – you can do this instead:And then in your application setup you can call
init_app:This way you can avoid cyclical imports.
This pattern does not necessitate the you place all of your models in one file. Simply import the
dbvariable into each of your model modules.Example
Note: this is a sketch of some of the power this gives you – there is obviously quite a bit more that you can do to make development even easier (using a
create_apppattern, auto-registering blueprints in certain folders, etc.)