Python flask get all parameters from url

how i can parse all GET params from URL in flask? I tried use request.args.get, but it works with specific GET params (pre defined), but i need parse it all from my large URL (ex: http://site.ru/?a=1&b=2&c=3&some_string=string...)

asked Dec 19, 2016 at 19:31

Python flask get all parameters from url

If you use request.args it will provide a dictonary with key-value pairs of the GET parameters

Ex: http://website.com/index?arg1=hello&arg2=world

print request.args
>> {"arg1": "hello", "arg2": "world"}

The request.args.get(key) is a useful dictionary function that will return None if the parameter is not set rather than raising a KeyError

answered Dec 19, 2016 at 19:33

Python flask get all parameters from url

0

[i for i in request.args.keys()]

answered May 20, 2020 at 10:35

Ishan TomarIshan Tomar

1,4201 gold badge16 silver badges20 bronze badges

Query Parameters are part of the Query String - a section of the URL that contains key-value pairs of parameters. Typically, parameters are sent alongside GET requests to further specify filters on the operation:

www.example.com/search?name=John&location=Miami

The parameters are defined after the ? character and each key-value pair is separated with a &. Spaces are represented as %20 and can also be represented as +. These map to a key-value set of:

name=John
location=Miami

It's easy to manipulate the URL with JavaScript - so more often than not, query parameters are added as filters to searches. Additionally, by adjusting the content on the screen based on reproducible parameters, instead of the body of a request, results are shareable between users just by sending a link with the parameters!

For instance, on AirBnB - if you're fully flexible on the location, dates and wish for an auto-suggest, a click of a button leads you to:

https://www.airbnb.com/s/homes?refinement_paths%5B%5D=%2Fhomes&date_picker_type=flexible_dates&search_mode=flex_destinations_search&search_type=AUTOSUGGEST

There are a few parameters here, such as refinement_paths, date_picker_type, search_mode, and search_type, each with a value.

In this short guide, we'll take a look at how to get a GET Request's Query Parameters in Flask.

Get Query Parameters in Flask

from flask import Flask, request
# ...
@app.route('/search', methods=['GET'])
def search():
    args = request.args
    return args

The request.args field is an ImmutableMultiDict:

print(type(args))
# <class 'werkzeug.datastructures.ImmutableMultiDict'>

It can easily be converted into a regular dictionary via:

print(type(args.to_dict()))
# <class 'dict'>

Additionally, you can search for a specific key in the dictionary via the get() method, returning an error if the key doesn't match up to the preconceived argument list:

print(args.get("name"))
# John

You can additionally cast the value to a different type, such as int or str while getting it. You can also set a default value if the value isn't present already. For instance, a name parameter will probably be a string, but the price parameter might be an integer:

args.get("name", default="", type=str)
args.get("price", default=0, type=int)

If you search for a non-existent key - a None is returned. This way, you can check whether a query parameter is missing, and act accordingly - assigning a default value or just not using it.

Let's send a GET request to the endpoint with a name and location:

$ curl "localhost:5000/search?name=John&location=Miami"

This results in:

{"location":"Miami","name":"John"}

Check if Query Parameters are Not None

When operating on parameters, you'll typically want to check if they're None and act accordingly. This can thankfully easily be done by getting an expected key and checking if it's present in the dictionary!

Let's create a mock database - just a dictionary of users and their locations. Then, based on the parameters passed in the URL, we'll filter this dictionary and return the matching users that fit the criteria defined by the parameters:

from flask import Flask, request
# ...
db_users = {
    "John" : "Miami",
    "David" : "Miami",
    "Jane" : "London",
    "Gabriella" : "Paris",
    "Tanaka" : "Tokyo"
}

@app.route('/search', methods=['GET'])
def search():
    args = request.args
    name = args.get('name')
    location = args.get('location')

    # result = db_users
    if None not in (name, location):
        result = {key: value for key, value in db_users.items() if key == name and value == location}
    elif name is not None:
        result = {key: value for key, value in db_users.items() if key == name}
    elif location is not None:
        result = {key: value for key, value in db_users.items() if value == location}

    return result

Here - we extract the name and location from the parameter list. If none are present - you may wish to return all of the users, or none at all. If you'd wish to return all of them - uncomment the result = db_users line.

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

If both the name and location are present, we filter the db_users by both parameters. If only one is present - we filter it only using the present parameter.

Now, if we send a GET Request with both or a single parameter, we'll be greeted with:

$ curl "localhost:5000/search?name=John&location=Miami"
{"John":"Miami"}

$ curl "localhost:5000/search?name=John"
{"John":"Miami"}

$ curl "localhost:5000/search?location=Miami"
{"David":"Miami","John":"Miami"}

Two people are located in Miami, so just using the single search parameter nets us two users. There's only one John in the dictionary, so only John is returned for the first two queries.

Conclusion

In this guide, we've taken a look at how to get the query parameters of an HTTP GET Request in Flask.

We've also taken a look at how to check whether the parameters are None and how to handle the lack thereof with a mock database.

How can I get the named parameters from a URL using Flask?

In the first one we would use request. args. get('<argument name>') where request is the instance of the class request imported from Flask. Args is the module under which the module GET is present which will enable the retrieve of the parameters.

How do you pass multiple parameters in a Flask URL?

To add multiple parameters in a Python Flask app route, we can add the URL parameter placeholders into the route string. @app. route('/createcm/<summary>/<change>') def createcm(summary=None, change=None): #... to create the createcm view function by using the app.

Tải thêm tài liệu liên quan đến bài viết Python flask get all parameters from url