0

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):
...
1
  • 2
    why do you want to do this? Commented Jan 4, 2016 at 9:19

3 Answers 3

7

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)
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you. This is exactly what I looked for. :)
is_callable is not defined
Wow, amazed that survived this long! Thanks for helping make the answer better!
This is a good answer, I ended up revamping it to use type annotations and inspection to drop the need for having to list the arguments in the decorator, see my other answer about "flask-publisher".
1

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')

1 Comment

This is not an answer. The question specifically asks for being able to pass query parameters as parameters to the function.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.