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): ...
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 wrapsdef 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 wrapperreturn decorator if len(names) < 1 or not 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 applicationresults = {}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)