'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): ...
Solution 1:[1]
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 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
Usage:
@app.route("/somewhere")
@extract_args("gender", age=int)
def somewhere(gender, age):
return jsonify(gender=gender, age=age)
Solution 2:[2]
Flask views themselves do not have obligatory args. You can write:
from flask import request
@app.route("/user")
def getUser():
age = request.args.get('age')
gender = request.args.get('gender')
Solution 3:[3]
You can do this by getting Flask-Publisher and adding "@publish()" decorator before your getUser function:
from publisher import publish
@app.route("/user")
@publish()
def getUser(age:int, gender):
...
This uses inspection to get the arguments, optionally uses type annotations to convert the incoming arguments, and pulls the values from the GET/POST data.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Jean-François Fabre |
Solution 3 | Sean Reifschneider |