Flask and SQLAlchemy: init_app
I’ve been recently refactoring my Flask application and one of the most important changes I’ve made was an application factory. You can find out many different (but similar) syntax constructions to use SQLAlchemy with it. Here one and most common:
However, you might stumple upon this exception:
RuntimeError: application not registered on db instance and no application bound to current context,
perhaps in your tests on during
Documentation isn’t that clear on that matter. After a lot of searching I found out three options to solve this issue.
db object with
app as a parameter:
The drawback is that you don’t have a global
db object and thus your
blueprints won’t work. And you won’t be able to easily create models.
global db and then
db = SQLAlchemy(app) did not work
Assign created application to
The possible drawback: you might mess something up in
You don’t want that, do you?
db.create_all() (that’s the thing we had troubles with) within
The drawback: it’s
test_request_context (test!). But, after all, it
works fine for me. And all my tests pass! ;)
Use any method you want.
If you had this issue and you solved it another way, please let me know in the comments.
You will need to import models themselves before issuing
It’s a good idea to keep your
SQLAlchemy object instance in separate
file, to avoid circular imports: