python - 我可以在@app.before_request 中将值附加到我的烧瓶请求对象并将其转发给端点视图函数吗?
问题描述
我正在用 python 开发一些基本的 REST API。我希望在所有请求的标头中都有一个授权令牌,除了一些不安全的请求,如登录和注册。我正在验证 @app.before_request 中的令牌,然后我想将解码的有效负载传递给相应的端点视图函数。但是,当我得到“TypeError:'Request'对象不支持项目分配”时,我不会将解码的信息附加到请求对象。
@app.before_request
def before_request():
print(request.endpoint)
if request.endpoint=="register" or request.endpoint=="login":
pass
else:
auth_header = request.headers.get('Authorization')
if auth_header:
auth_token = auth_header.split(" ")[1]
token=decode_auth_token(auth_token)
request["token"]=token
else:
return jsonify({"result":"","error":"No token present in header !"})
我认为这个实现就像一个身份验证过滤器,所有请求都通过这个过滤器。我可以在这一层本身消除不良请求,还可以获取网络中间件所需的用户特定信息。
解决方案
I have a similar usecase (surprisingly similar, actually). I got around it by setting a custom property in the request object, much like your approach, although instead of using direct assignment (i.e. request["token"]=token
), I used setattr(request, "token", token)
.
I got the tip from a bottle plugin which does something very similar: https://github.com/agile4you/bottle-jwt/blob/master/bottle_jwt/auth.py#L258
You may even wanna try that, or some other plugin to further improve your application.