Flask 特定请求的回调函数

在Flask中before_request和after_request可以处理全局的请求前和请求结束的操作。但对于某些操作只想使用在特定的请求上,此时需要使用request回调函数。

after_this_request(f)指当前请求的回调函数,可以用来修改response数据。after_this_request可以在一个请求内任意时间任意地点创建。

@app.route('/this_request_callback')
def this_request_callback():
    @after_this_request    
    def callback(response):
        print(response.headers, response.data)
        return response # 必须返回response,或者构建一个新的response对象返回。    
    return '123'


还可以对返回的response进行修改。比如某一视图方法返回需要记录特定的cookies值。

@app.route('/this_request_callback')
def this_request_callback():
    @after_this_request    
    def callback(response):
        response.headers['Content-Type'] = 'application/octet-stream'        
        response.data = b'xyz'        
        return response # 必须返回response,或者构建一个新的response对象返回。    
    return '123'


在请求内任意位置时间创建

@app.route('/this_request_callback')
def this_request_callback():
    return '123'
    @app.before_requestdef 
    before_req():
        print('before request...')

    @after_this_request    
    def callback(response):
        response.set_cookie('123', 'abc')
        return response  # 必须返回response,或者构建一个新的response对象返回。

展开阅读全文