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
Solution 1:
If you are willing to write a decorator, anything is possible:
from functools import wraps
defextract_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()])
defdecorator(f):
@wraps(f)defwrapper(*args, **kwargs):
final_args, final_kwargs = args_from_request(user_args, args, kwargs)
return f(*final_args, **final_kwargs)
return wrapper
return decorator iflen(names) < 1ornotcallable(names[0]) else decorator(names[0])
defargs_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
Usage:
@app.route("/somewhere")
@extract_args("gender", age=int)
def somewhere(gender, age):
return jsonify(gender=gender, age=age)
Post a Comment for "Get Query String As Function Parameters On Flask"