简体   繁体   English

将查询参数传递给Flask装饰器

[英]Pass query parameters to Flask decorator

I'm setting up a token auth system for my Flask server, and I want to be able to setup a decorator to look something like this: 我正在为Flask服务器设置令牌身份验证系统,并且希望能够设置装饰器,使其看起来像这样:

@app.route('/my/data/')
@requires_token_auth
def get_my_endpoint_data():
    """Return JSON data""""
    return get_data()

Then I'll hit the endpoint like /my/data?token=myawesometokenvalue 然后我将击中端点,如/ my / data?token = myawesometokenvalue

I've setup my decorator function like 我已经设置了我的装饰器功能

def requires_token_auth(f):
    @wraps(f)
    def wrapped(*args, **kwargs):
        ... do stuff ...
        return f(*args, **kwargs)
return wrapped

Unfortunately, the 'token' parameter is not made available inside of args. 不幸的是,'token'参数在args内部不可用。 The problem seems to be that Flask passes the req.view_args through, instead of req.args. 问题似乎是Flask通过了req.view_args而不是req.args。

* From flask's app.py * *来自flask的app.py *

1344         return self.view_functions[rule.endpoint](**req.view_args)

How can I access query parameters from inside of a wrapped function? 如何从包装函数内部访问查询参数?

Since this is the first google result for "flask query parameters decorator", this is the solution I ended up with to add the query parameters, on top of path parameters in methods: 由于这是“烧瓶查询参数修饰器”的第一个google结果,因此这是我最终在方法的路径参数之上添加查询参数的解决方案:

def query_params(f):
    """
    Decorator that will read the query parameters for the request.
    The names are the names that are mapped in the function.
    """
    parameter_names = inspect.getargspec(f).args

    @wraps(f)
    def logic(*args, **kw):
        params = dict(kw)

        for parameter_name in parameter_names:
            if parameter_name in request.args:
                params[parameter_name] = request.args.get(parameter_name)

        return f(**params)

    return logic

@app.route('/hello/<uid>', methods=['GET', 'POST'])
@query_params
def hello_world(uid, name):
    return jsonify({
        'uid': uid,
        'name': name
    })

哦,我才意识到我可以像往常一样做!

token = request.args.get('token')

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

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