简体   繁体   English

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

[英]Flask add parameter to view methods in before_request

Lets say I have an API at /api/something. 假设我在/ api /某个地方有一个API。 The API requires a definition for api_key, it looks in the request arguments and the cookies. API需要api_key的定义,它在请求参数和cookie中查找。 If it finds the api_key, I want it to pass the api_key to the route methods, in this case something . 如果找到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

Is this possible? 这可能吗?

Thanks in advance. 提前致谢。

One way to do this would be to use flask.g . 一种方法是使用flask.g From the docs : 来自文档

To share data that is valid for one request only from one function to another, a global variable is not good enough because it would break in threaded environments. 要共享仅对一个请求有效的数据从一个函数到另一个函数,全局变量不够好,因为它会在线程环境中中断。 Flask provides you with a special object that ensures it is only valid for the active request and that will return different values for each request. Flask为您提供了一个特殊对象,确保它仅对活动请求有效,并为每个请求返回不同的值。

Set g.api_key to the value you want to store in before_request and read it out in the route method. g.api_key设置为您要在before_request存储的值,并在route方法中读出它。

flask.g , like flask.request , is what Flask and Werkzeug call a "context local" object - roughly, an object that pretends to be global, but really exposes different values to each request. flask.g ,就像flask.request一样,是Flask和Werkzeug所谓的“上下文本地”对象 - 粗略地说,这个对象假装是全局的,但实际上为每个请求公开了不同的值。

This can be done using the url_value_processor decorator: 这可以使用url_value_processor装饰器完成:

@app.url_value_preprocessor
def get_project_object(endpoint, values):
    api_key = values.get('api_key')
    if api_key is None:
        api_key = request.cookies.get('api_key', None)
    if api_key is None:
        raise Exception('api_key is required')
    values['api_key'] = api_key

This can also be done in a Blueprint basis, so that it only applies to the views in the specified Blueprint. 这也可以在蓝图的基础上完成,因此它仅适用于指定蓝图中的视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM