Analysis of request Request Hook and Context Usage in Flask Framework

  • 2021-07-26 08:00:38
  • OfStack

This article illustrates request, request hook and context usage in Flask framework. Share it for your reference, as follows:

request

Is the request object in flask that represents the current request:

Common attributes are as follows:

属性 说明 类型
data 记录请求的数据,并转换为字符串 *
form 记录请求中的表单数据 MultiDict
args 记录请求中的查询参数 MultiDict
cookies 记录请求中的cookie信息 Dict
headers 记录请求中的报文头 EnvironHeaders
method 记录请求使用的HTTP方法 GET/POST
url 记录请求的URL地址 string
files 记录请求上传的文件 *

Request hook

The request hook of flask is actually very similar to the middleware of django.

In the process of client-server interaction, some preparatory work or finishing work needs to be dealt with, such as: at the beginning of the request, establish a database connection; At the end of the request, specify the interactive format of the data. To prevent each view function from writing duplicate functionality, Flask provides the functionality of a common facility, the request hook.

Request hooks are implemented in the form of decorators, and Flask supports the following four request hooks:

before_first_request: Run before processing the first request. before_request: Run before each request. after_request: Run after each request if no unhandled exceptions are thrown. teardown_request: Run after each request, even if an unhandled exception is thrown.

Implementation of decorator routing

Flask has two cores: Werkzeug and Jinja2

-Werkzeug implements routing, debugging, and Web server gateway interfaces
-Jinja2 implements templates.

Werkzeug is an python function library that follows WSGI protocol

-It implements a lot of things underneath the Web framework, such as request and response objects;
-Compatibility with WSGI specification; Support Unicode;
-Support basic session management and signature Cookie;
-Integrated URL request routing, etc.

The routing module of the Werkzeug library is responsible for implementing URL parsing. Different URL corresponds to different view functions, and routing module will analyze URL requesting information and match it to the view function corresponding to URL, so as to generate a response information.

The routing module contains:

-Rule class (objects used to construct different URL schemas)
-Map class (stores all URL rules)
-Subclass of BaseConverter (responsible for defining matching rules)
-MapAdapter class (responsible for specific URL matching)

Context

Context: Equivalent to a container, saving Flask program in the process of running a number of information.

There are two contexts in Flask, the request context and the application context.

Request Context (request context)

Flask When a request is received from a client, the view function should have access to 1 object so that the request can be processed. A good example is the request object, which encapsulates the HTTP request sent by the client.

An obvious way for a view function to access the requested object is to pass it as an argument to the view function, but this causes each view function in the program to add an argument, which is worse if the view function accesses other objects besides the requested object while processing the request. To avoid making the view function a mess with a large number of optional parameters, Flask uses context to temporarily make certain objects globally accessible.

request and session are both request context objects. request: Encapsulates the contents of an HTTP request, for an http request. Example: user = request. args. get ('user'), which gets the parameters of the get request. session: Used to record information in the request session, for user information. Example: session ['name'] = user. id, which can record user information. User information can also be obtained through session. get ('name'). When app = Flask (name) is called, the program application object app is created; request WSGI server tunes Flask. call () each time an http request occurs; The request object that is then created inside the Flask; The life cycle of app is longer than that of request. During the survival of one app, multiple http requests may occur, so there will be multiple request. Eventually, the view function is passed in, and the response object is generated by return, redirect, or render_template, which is returned to the client.

Application Context (application context)

It literally means application context, but it does not exist directly. It is only a proxy (person) of app in request context, so-called local proxy. Its main function is to help request get the current application. It was born with request and died with request.

The application context objects are: current_app, g

current_app

Application context, used to store variables in the application, you can print the name of the current app through current_app. name, or you can store 1 variables in current_app, for example:

Which file is the startup script of the application and what parameters are specified at startup Which configuration files were loaded and which configurations were imported Which database is connected to What are the public tool classes, constants On which machine does the application run, how much is IP, and how much is the memory

current_app.name
current_app.test_value='value'

g variable

As a temporary variable of flask program, g acts as a medium, we can pass some data through it. g stores the global variable of the current request, and different requests will have different global variables, which are distinguished by different thread and id


g.name='abc'

The difference between the two:

Request context: Saves the data of client-server interaction
Application context: 1 configuration information saved in the running process of flask application, such as program name, database connection, application information, etc.

Request context and application context principle implementation: https://segmentfault.com/a/1190000004223296

I hope this article is helpful to the Python programming based on flask framework.


Related articles: