/ Python

Python Flask Series - Routing in Flask - P4

This will be part 4 of our Flask Series where we will go into Routing.

Flask Routing is essentially mapping a URL eg. example.com/index/test to a certain piece of code. For example having /contact-us displaying a page about contact details.

The route() decorator in Flask is used to bind the URL to a function.

Some Basic Examples:

This is a basic static web app that shows on which page you are:

from flask import Flask

app = Flask(__name__)

@app.route('/home')
def home():
    return '<h2>You are on the Home Page</h2>

@app.route('/about-us')
def about():
    return '<h2>You are on the About Us Page</h2>'

if __main__ == '__name__':
    app.run()
``` <p>

So when you do a GET Request on `http://localhost:5000/home` you will be presented with the response that you are on the home page.

This is all good and well, but its static, so lets look how we can set this up in a dynamic way.

**URL Variables:**

We can use variables in the `route()` decorator which we can parse through to the function. In this next example we will use a `name` variable, and depending on what name is passed in the GET request, will be provided in the response.

```language-python
from flask import Flask
app = Flask(__name__)

@app.route('/user/<name>')
def user(name):
    return 'Welcome, %s' % (name)

if __main__ == '__name__':
    app.run()
``` <p>

So with the above example, `<name>` will be used as a placeholder or variable, and then passed through to our function and then printed in our response, for example:

```bash
$ curl -XGET http://localhost:5000/user/James
Welcome, James

$ curl -XGET http://localhost:5000/user/Frank
Welcome, Frank

So this can be really useful when dealing with dynamic data. You can also go deeper into this, like the following:

from flask import Flask
app = Flask(__name__)

@app.route('/user/<name>/<surname>/<prog_lang>')
def user(name, surname, prog_lang):
    return '%s %s likes %s' % (name, surname, prog_lang)

if __main__ == '__name__':
    app.run()

This will produce:

$ curl -XGET http://localhost:5000/user/John/Smith/Python
John Smith likes Python

We can also have defaults, so if no values was passed, and you only hit the '/user' endpoint, you can have a default value returned:

from flask import Flask
app = Flask(__name__)

@app.route('/user', defaults={'name': 'Ruan', 'surname': 'B', 'prog_lang': 'Python'})
@app.route('/user/<name>/<surname>/<prog_lang>')
def user(name, surname, prog_lang):
    return '%s %s likes %s' % (name, surname, prog_lang)

if __main__ == '__name__':
    app.run()

So then the output would look like this:

$ curl -XGET http://localhost:5000/user
Ruan B likes Python

This is a very simple example, but you could use it in many ways.

Data Types in URL Routing:

You could also explicitly set your datatypes, like string or integer etc in your route decorators.

  • For strings:
from flask import Flask
app = Flask(__name__)

@app.route('/city/<string:cityname>')
def user(cityname):
    return 'Selected City is: %s' % (cityname)

if __main__ == '__name__':
    app.run()
  • For Integers:
from flask import Flask
app = Flask(__name__)

@app.route('/user/<integer:age>')
def user(age):
    return 'Selected age is: %i' % (age)

if __main__ == '__name__':
    app.run()

And now because the datatype is an integer, when you try to pass a string, you will be faced with an error. So the value that you will need to pass would then be strictly set to the type of integer.

  • IF Statements

You could also use if statements in your functions, like determining the age group, for example:

from flask import Flask
app = Flask(__name__)

@app.route('/user/<integer:age>')
def user(age):
    if age >= 28:
        return 'Your selected age is %i, so you are in the 28 and older group' % (age)
    else:
        return 'Your selected age is %i, so you are in the younger then 28 group' & (age)

if __main__ == '__name__':
    app.run()

So with the above example:

$ curl -XGET http://127.0.0.1:5000/user/12
Your selected age is 12, so you are in the younger then 28 group

$ curl -XGET http://127.0.0.1:5000/user/30
Your selected age is 30, so you are in the 28 and older group
  • For Floats:
@app.route('/myfloat/<float:floatnum>')
  • Path Types

We can also pass accept the URL Path, that is passed by using the path type:

from flask import Flask
app = Flask(__name__)

@app.route('/path/<path:mypath>')
def user(mypath):
    return 'Your selected path is: ' + '/' + '%s' & (mypath)

if __main__ == '__name__':
    app.run()

So with the above example:

$ curl -XGET http://127.0.0.1:5000/path/apps/data/my/app
Your selected path is: /apps/data/my/app

Interaction with MongoDB:

With the above examples you can use this method to push and retrieve data from a Database like MongoDB, I will leave that for another post, but you can have a look at a full example on how I played around with it on my Git Repository

Our Next Post will be about Requests, which should be coming soon.

Tag: Flask-Series