问题描述
来自使用 Spark 的Java开发,我能够在中附加自定义属性请求
(servlet API)实例传递给处理程序.
Coming from Java development using Spark, I was able to attach custom attributes in the Request
(servlet API) instance that gets passed to a handler.
现在,在Flask(Python)中,我们得到一个包含特定请求详细信息的全局 request
对象.我有一个 @ app.before_request
装饰器,它需要基于给定的API令牌创建一个自定义用户对象,并将其附加到目标处理程序可以访问的请求上.
Now, in Flask (Python), we get a global request
object containing the details of the particular request. I have a @app.before_request
decorator that needs to create a custom user object based on a given API token and attach it to the request to be accessed by target handlers.
@app.before_request
def check_api():
if 'Authorization' in request.headers:
token = request.headers['Authorization']
if token:
user = verify_and_get_user(token)
request['user'] = user
@app.route('/resources/create', methods=['POST'])
def create_resource():
print('- User with id %s created a resource' % request['user'].id)
如何以线程安全的方式执行上述操作?
How can I do something like the above, in a thread safe manner?
推荐答案
您可以在请求期间使用 g
全局命名空间对象存储和共享资源.此处.
You can store and share resources during a request by using the g
global namespace object. More details here.
您必须首先将其导入:从flask导入g
.
You will have to import it first: from flask import g
.
您可以在此处找到一些用法示例.
You can find some usage examples here.
这篇关于如何在Flask中为请求设置属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!