将查询参数传递给Flask装饰器 [英] Pass query parameters to Flask decorator
问题描述
我正在为我的Flask服务器设置一个令牌身份验证系统,并且我希望能够设置一个装饰器,使其看起来像这样:
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:
@app.route('/my/data/')
@requires_token_auth
def get_my_endpoint_data():
"""Return JSON data""""
return get_data()
然后,我将按/my/data?token = myawesometokenvalue这样的终点
Then I'll hit the endpoint like /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
不幸的是,'token'参数在args内部不可用.问题似乎是Flask通过了req.view_args,而不是req.args.
Unfortunately, the 'token' parameter is not made available inside of args. The problem seems to be that Flask passes the req.view_args through, instead of req.args.
*来自烧瓶的app.py *
1344 return self.view_functions[rule.endpoint](**req.view_args)
如何从包装函数内部访问查询参数?
How can I access query parameters from inside of a wrapped function?
推荐答案
由于这是烧瓶查询参数修饰器"的第一个google结果,因此这是我最终在路径顶部添加查询参数的解决方案方法中的参数:
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:
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
})
这篇关于将查询参数传递给Flask装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!