Query Strings

Sending arguments and variables to URLs is important. Users can do that using Query Strings which are the parts in the URL coming after the question mark. To use query strings, first we have to import the request object.

#[simple_app.py]:
from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/')
def index(name="Treehouse"):
 name = request.args.get('name', name)
 return "Hello from {}".format(name)

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

In the request object, there is an attribute called args that handles all the arguments in the request.
Like in dictionaries, use the .get function to get the sent values.

Test URL

Now if we change the query string in the URL:

treehouse-app.com/?name=Bashar

We get on the webpage:

Hello from Bashar

 


 Clean URL Arguments

Let’s get rid of the question mark in the query string, and let’s use a more practical way to write a URL.

Request: Arguments are passed to the function/view through the URL bar
Response: View is returned accordingly.

from flask import Flask

app = Flask(__name__)

@app.route('/')
@app.route('/<name>')
def index(name="Treehouse"):
  return "Hello from {}".format(name)

# Multiple routes too
@app.route('/add/<int:num1>/<int:num2>')
@app.route('/add/<int:num1>/<float:num2>')
@app.route('/add/<float:num1>/<int:num2>')
@app.route('/add/<float:num1>/<float:num2>')
def add(num1, num2):
  return "{} + {} = {}".format(num1, num2, num1+num2)

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

Note: Naturally, Requests are received only in strings, and Responses are returned only in strings as well.