Fine Radar
The News Hub

Access the Query String in Flask Routes – GeeksforGeeks

Improve Article

Save Article

Like Article

Improve Article

Save Article

In this article, we are going to see how to Access the Query String in Flask Routes in Python. The query string is the portion of the URL and Query Parameters are part of the query string that contains the key-value pair.

Example:

http://127.0.0.1:50100/?name=isha&class=10

After ? character, everything is a query parameter separated by &. Here name=isha and class=10 are query parameters. 

In Flask, we can use the request.query_string attribute of the request object to access the raw query string in the URL. We can use it like this:

Python3

from flask import Flask, request

  

app = Flask(__name__)

  

@app.route('/')

def search():

    query_string = request.query_string

    return f'Query string: {query_string}'

  

if __name__ == '__main__':

    app.run(host='0.0.0.0', port=50100, debug=True)

This will return the following response:

Output1

We can use the request.args if we want to access the individual parameter keys and values which is a dictionary that maps the parameter names to their values. We can use it like this:

@app.route('')
def search():
    name = request.args.get('name')
    clas = request.args.get('class')
    return f'Searching : name {name}, class {clas}'

The output will look like this:

Output2

We can also use the request.args.getlist method to retrieve a list of values for a parameter, if the parameter has multiple values. 

For example:

Python

from flask import Flask, request

  

app = Flask(__name__)

  

@app.route('/')

def search():

    query = request.args.getlist('name')

    return f'Name: {query}'

  

if __name__ == '__main__':

    app.run(host='0.0.0.0', port=50100, debug=True)

The following will be its output:

Output3

 

Stay connected with us on social media platform for instant update click here to join our  Twitter, & Facebook We are now on Telegram. Click here to join our channel (@TechiUpdate) and stay updated with the latest Technology headlines. For all the latest Technology News Click Here 

Read original article here

Denial of responsibility! FineRadar is an automatic aggregator around the global media. All the content are available free on Internet. We have just arranged it in one platform for educational purpose only. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials on our website, please contact us by email – [email protected]. The content will be deleted within 24 hours.
Leave A Reply

Your email address will not be published.