This article is mainly on the flask before_request and after_request usage to do a simple analysis of specific examples and introduction as follows.
Using both before_request and after_request is very simple, use @app.before_request [email protected]_request to qualify the function that is expected to execute before or after the request
Example:
@app.before_request def before_request(): if not m_ip_range.is_ip_strict(): return ranges = m_ip_range.get_range() ip_int = utils.ip_to_int(request.remote_addr) yes = False for item in ranges: if item['is_used']==0: continue if ip_int >= item['ip_start'] and ip_int <= item['ip_end']: yes = True break if not yes: abort(400)
After the before_request() function is modified, it will be executed first after each request arrives, and if it's okay, i.e., it doesn't execute to abort(400), then it will go to the normal modified function to respond, and if more than one function is modified by app.before_request, then these functions will be executed sequentially.
You are very concerned about what this before_request decorator, in fact, it is very useful, for example, we want to be able to filter ip addresses, although you can use nginx, but we can also use before_request to do so, using nginx, we have to manually set up, but if it is to use flask's own before_request mechanism, we can add the program to the cache after determining that an ip has malicious access (redis), each time a request comes by before_request. But if we use flask's own before_request mechanism, we can add an ip to the cache (redis) after the program determines that the ip has malicious access behavior, and each time a request comes in, before_request to determine whether the ip is legitimate.
app.after_request modified function will be in the request to get the corresponding return to the user before being called, that is to say, at this time, the request has been decorated function response, has formed a response, we do some operations at this time, flask has a plug-in called flask-compress, is the response to the result of the compression, it is with after_request of this mechanism, in the response before the return of the data compression, if you have other things you want to operate, you can also use after_request to complete.
summarize
Above is this article on the flask before_request and after_request all content, I hope you can help. Interested friends can continue to refer to other related topics on this site, if there are inadequacies, welcome to leave a message to point out. Thank you for the support of friends on this site!