Python flask intercepts before request

The methods of using before_request and after_request are very simple. Use @app.before_request or @app.after_request to modify the function that is expected to be executed 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. If there is no problem, that is, abort(400) is not executed, then it will enter the normal function modified by app.route to respond. If There are multiple functions modified by app.before_request, then these functions will be executed in sequence.

    You are very concerned about the use of this before_request decorator. In fact, it is very useful. For example, we hope to filter ip addresses. Although you can use nginx, we can also use before_request to do it. With nginx, we have to manually However, if we use flask's own before_request mechanism, we can add it to the cache (redis) after the program determines that an ip has malicious access behavior. Every time a request comes, the ip is judged by before_request. Is it legal.

 

    The function decorated with app.after_request will be called before returning to the user after the request is received. That is to say, at this time, the request has been responded by the function decorated with app.route, and a response has been formed. At this time, we have To do some operations, flask has a plugin called flask-compress, which compresses the response results. It uses the mechanism of after_request to compress the data before the response returns. If you have other things you want to operate, The same can be done using after_request.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325341577&siteId=291194637