编程语言
首页 > 编程语言> > python after_request详解

python after_request详解

作者:互联网

after_request是在每一个请求结束之后,再请求的一个钩子函数。
它需要有一个参数接收请求的响应。
这个示例是使用after_request,对每一个请求后的响应进行分类,
从而在请求完成之后,做不同的操作。

演示代码

import json
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route("/test1", methods=['POST'])
def t1():
    data = request.get_json(force=True)
    env = data.get('env')
    return {'code': 0000,'env': env}
@app.route("/test2")

def t2():
    env = request.args.get('env')
    return {'code': 0000,'env': env}

@app.after_request
def after(response):
    return_str = response.data.decode("utf-8")
    return_dict = json.loads(return_str)
    if return_dict['env'] == 't1':
        return_dict['todo'] = 'change nginx'
    elif return_dict['env'] == 't2':
        return_dict['todo'] = 'update mysql'
    else:
        return_dict['todo'] = 'send mq'
    return jsonify(return_dict)
if __name__ == "__main__":
    app.run()

  

演示结果
C:\Users\jh>curl -H "Content-type: application/json" -d "{\"env\":\"t1\"}" http://127.0.0.1:5000/test1
{"code":0,"env":"t1","todo":"change nginx"}

C:\Users\jh>curl http://127.0.0.1:5000/test2?env=t2
{"code":0,"env":"t2","todo":"update mysql"}

C:\Users\jh>curl http://127.0.0.1:5000/test2?env=t7
{"code":0,"env":"t7","todo":"send mq"}

标签:__,return,python,after,request,dict,env,todo
来源: https://www.cnblogs.com/mtck/p/16631811.html