在烧瓶上获取查询字符串作为函数参数 [英] Get query string as function parameters on flask
本文介绍了在烧瓶上获取查询字符串作为函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法在烧瓶上获取查询字符串作为函数参数?
例如,请求将是这样.
Is there a way to get query string as function parameters on flask?
For example, the request will be like this.
http://localhost:5000/user?age=15&gender=Male
并希望与此类似的代码.
And hope the code similar to this.
@app.route("/user")
def getUser(age, gender):
...
推荐答案
如果您愿意编写装饰器,则一切皆有可能:
If you are willing to write a decorator, anything is possible:
from functools import wraps
def extract_args(*names, **names_and_processors):
user_args = ([{"key": name} for name in names] +
[{"key": key, "type": processor}
for (key, processor) in names_and_processors.items()])
def decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
final_args, final_kwargs = args_from_request(user_args, args, kwargs)
return f(*final_args, **final_kwargs)
return wrapper
return decorator if len(names) < 1 or not is_callable(names[0]) else decorator(names[0])
def args_from_request(to_extract, provided_args, provided_kwargs):
# Ignoring provided_* here - ideally, you'd merge them
# in whatever way makes the most sense for your application
results = {}
for arg in to_extract:
result[arg["key"]] = request.args.get(**arg)
return provided_args, results
用法:
@app.route("/somewhere")
@extract_args("gender", age=int)
def somewhere(gender, age):
return jsonify(gender=gender, age=age)
这篇关于在烧瓶上获取查询字符串作为函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文