On before_request and after_request in flask

  • 2020-07-21 09:01:40
  • OfStack

This paper mainly makes a simple analysis of the usage of before_request and after_request in flask. The concrete examples and introduction are as follows.

The methods using before_request and after_request are very simple, using either @app.before_request or @app.after_request to modify functions that are expected to be executed before or after a 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 decorated, it is executed every time a request arrives. If there is no problem, it is not executed to abort(400), then it is returned to the normal app.route decorated function. If more than one function is decorated by ES28en.before_request, then these functions are executed in turn.

What's the use of you are very concerned about the before_request decorator, but its use is very big, such as we hope that we can to ip address filtering, although you can use nginx, but we can also use before_request to do, use nginx, we have to be set manually, but if it is using flask before_request mechanism of itself, we can determine that the program after a ip have malicious access behavior to be added to the cache (redis), each request arrives, before_request determines whether this ip is legal or not.

Will be app. after_request modified function before the request is returned to the user after is called, that is to say, this time, the request has been app. route illuminative function response, has formed the response, 1 at this time we do some operation, flask have a plug-in called flask - compress, is to compress the response results, the mechanism of it is to use after_request, before response returns on data compression, If you want to do something else, use after_request.

conclusion

Above is the paper on before_request and after_request all content, hope to help you. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out. Thank you for your support!


Related articles: