- Flask Framework Cookbook(Second Edition)
- Shalabh Aggarwal
- 185字
- 2021-06-24 13:58:04
There's more...
Sometimes, you may want a single SQLAlchemy db instance to be used across multiple applications, or create an application dynamically. In such cases, we might not prefer to bind our db instance to a single application. Here, we will have to work with the application context to achieve the desired outcome.
In this case, we will register our application with SQLAlchemy differently as follows:
from flask import Flask from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() def create_app(): app = Flask(__name__) db.init_app(app) return app
The preceding approach can be taken up while initializing the app with any Flask extension, and is very common when dealing with real-life applications.
Now, all the operations that were earlier possible globally with the db instance will now require a Flask application context at all times.
The Flask application context is as follows:
>>> from my_app import create_app >>> app = create_app() >>> app.test_request_context().push() >>> # Do whatever needs to be done >>> app.test_request_context().pop()
Or, we can use context manager, shown as follows:
with app(): # We have flask application context now till we are inside the with block