flask
what is a flask application
a flask application is a normal, just a normal python object of class Flask. An instance of this class will be our WSGI application.
here is the simplest way to create a Flask instance
from flask import Flaskapp = Flask(__name__)it's the object app that takes the responsibility to handle requests
须要留意的是,在项目中,app是一个顶层对象
request context
- When the Flask application handles a request, it creates a Request object based on the environment it received from the WSGI server.
- Because a worker (thread, process, or coroutine depending on the server) handles only one request at a time, the request data can be considered global to that worker during that request. Flask uses the term context local for this.
- Flask automatically pushes a request context when handling a request. View functions, error handlers, and other functions that run during a request will have access to the request proxy, which points to the request object for the current request.
If you try to access request, or anything that uses it, outside a request context, you’ll get this error message:
RuntimeError: Working outside of request context.
refer to https://flask.palletsprojects.com/en/2.2.x/reqcontext/
application context
Flask automatically pushes an application context when handling a request.
View functions, error handlers, and other functions that run during a request will have access to current_app, which is a proxy, pointing to the bound app.
Flask will also automatically push an app context when running CLI commands registered with Flask.cli using @app.cli.command().
Working outside of application context
If you try to access current_app, or anything that uses it, outside an application context, you’ll get this error message:
RuntimeError: Working outside of application context.
如果在配置应用的时间(如初始化扩展)看到这样的错误信息,可以手动推入一个上下文以访问 app。在 with 语句中使用 app_context() 上下文管理器对象,全部在块内的运行的代码将可以访问 current_app:
def create_app(): app = Flask(__name__) with app.app_context(): init_db() return apprefer to https://flask.palletsprojects.com/en/2.2.x/appcontext/#the-application-context
context in flask 就像 gin.context
区别在于,flask框架的extension都依赖context,换句话说,flask extension都创建在context之上;而gin框架只有http handler依赖gin.context,把须要的值从 context 拿出来之后交到业务逻辑层,就与 context 无关了
Lifetime of the Context
The application context is created and destroyed as necessary.
- When a Flask application begins handling a request, it pushes an application context and a request context.
- When the request ends it pops the request context then the application context. Typically, an application context will have the same lifetime as a request.
|