有没有办法将查询字符串作为烧瓶上的函数参数? 例如,请求将是这样的。
http://localhost:5000/user?age=15&gender=Male
希望代码与此类似。
@app.route("/user") def getUser(age, gender): ...
答案 0 :(得分:3)
如果你愿意写一个装饰者,一切皆有可能:
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)
答案 1 :(得分:1)
你真的需要它们作为函数参数吗?烧瓶视图本身没有强制性的args。你可以写:
from flask import request
@app.route("/user")
def getUser():
age = request.args.get('age')
gender = request.args.get('gender')