Flask添加参数以查看before_request中的方法

Pat*_*rio 8 python flask

假设我在/ api /某个地方有一个API.API需要api_key的定义,它在请求参数和cookie中查找.如果找到api_key,我希望它将api_key传递给路由方法,在本例中something.

@app.before_request
def pass_api_key():
    api_key = request.args.get('api_key', None)
    if api_key is None:
        api_key = request.cookies.get('api_key', None)
    if api_key is None:
        return 'api_key is required'
    # add parameter of api_key to something method

@app.route('/api/something')
def something(api_key):
    return api_key
Run Code Online (Sandbox Code Playgroud)

这可能吗?

提前致谢.

Joh*_*han 11

一种方法是使用flask.g.来自文档:

要共享仅对一个请求有效的数据从一个函数到另一个函数,全局变量不够好,因为它会在线程环境中中断.Flask为您提供了一个特殊对象,确保它仅对活动请求有效,并为每个请求返回不同的值.

设置g.api_key为要存储的值,before_request并在路径方法中读取它.

flask.g就像flask.requestFlask和Werkzeug所谓的"上下文本地"对象一样 - 粗略地说,这个对象假装是全局的,但实际上为每个请求公开了不同的值.