Requesting query arguments

As explained above a query string is the part after the question mark: 

https://www.google.com/search?q=python

Here in our case the app, by default, runs on 127.0.0.1:5000 so suppose we add a query string to /search route for performing a search, it will look like this with key query and value g4g

http://127.0.0.1:5000/search?query=g4g

Now we want to extract the value. For that we use request.args.get(‘query’) or request.args[‘query’] .
It is recommended to use request.args.get(‘query’) as the second will run into an 400 error if the query key is not provided.

So let’s make changes to our /search route

Python3




@app.route('/search')
def search():
    query = request.args.get('query')
  
    # passing the value to html code
    return render_template("search.html", query=query)


This will render this HTML code:

HTML




<!DOCTYPE html>
<html>
<head>
<title>Search</title>
</head>
<body>
  <h2>You searched for {{query}}</h2>
  <!-- {{query}} is the value returned from the search function -->
</body>
</html>


So after running the app and going to 

http://127.0.0.1:5000/search?query=g4g

will give this output:

 

How to Obtain Values of Request Variables in Flask

In this article, we will see how to request the query arguments of the URL and how to request the incoming form data from the user into the flask.

In a flask, to deal with query strings or form data, we use Request variables.

For example, a query string may look like this:

google.com/search?q=python

Let’s start by creating a demo flask project. To be able to request data we will need to import the request from the Flask library.

Python3




# importing Flask and request
# from the flask library
from flask import Flask, request, render_template  # to render html code
  
# pass current module (__name__)
# as argument to create instance of flask app
app = Flask(__name__)
  
# ‘/search’ URL is bound with search() function.
  
  
@app.route('/search'# for requesting query arguments
# defining a function search which returns the rendered html code
def search():
    return render_template("search.html")
  
# ‘/name’ URL is bound with name() function.
  
  
@app.route('/name'# for requesting form data
# defining a function name which returns the rendered html code
def name():
    return render_template("name.html")
  
  
# for running the app
if __name__ == "__main__":
    app.run(debug=True)


The route() function of the Flask class is a decorator, which tells the application which URL should call the associated function.
Here we have created two routes /search to request query arguments and /name to request form data.
We will update them as we move ahead. Again details can be understood from here.

Similar Reads

Requesting query arguments

...

Requesting form data

As explained above a query string is the part after the question mark:...

Summary

...

Contact Us