before_request 顾名思义,就是在request请求之前做的事情。
它会在每一个请求来的时候,都会先去请求before_request注册的函数。
before_request需要注册一个函数,可以不需要参数。
这个示例是在每个请求之前,做一个分类,不同环境来源的请求需要做
不同的事情。
演示代码
from flask import Flask,request app = Flask(__name__) @app.route("/test1", methods=['POST']) def t1(): data = request.get_json(force=True) env = data.get('env') print(env) return env @app.route("/test2") def t2(): env = request.args.get('env') print(env) return env @app.before_request def before(): res_method = request.method env = '' if res_method == 'GET': env = request.args.get('env') if res_method == 'POST': data = request.get_json(force=True) env = data.get('env') if env == 't1': print('before t1, I need change nginx') elif env == 't2': print('before t2,I need to update mysql') else: print('new env: %s, I need check it' % env) return None if __name__ == "__main__": app.run()
结果演示
C:\Users\jh>curl -H "Content-type: application/json" -d "{\"env\":\"t1\"}" http://127.0.0.1:5000/test1
t1
C:\Users\jh>curl http://127.0.0.1:5000/test2?env=t2
t2
C:\Users\jh>curl http://127.0.0.1:5000/test2?env=t7
t7
后台日志输出
127.0.0.1 - - [26/Aug/2022 19:41:28] "POST /test1 HTTP/1.1" 200 -
before t1, I need change nginx
t1
127.0.0.1 - - [26/Aug/2022 19:41:36] "GET /test2?env=t2 HTTP/1.1" 200 -
before t2,I need to update mysql
t2
127.0.0.1 - - [26/Aug/2022 19:41:40] "GET /test2?env=t7 HTTP/1.1" 200 -
new env: t7, I need check it
t7
before_request通常使用在验证登录,过滤请求攻击等方面
详细文档
https://dormousehole.readthedocs.io/en/latest/api.html#flask.Flask.before_request