Skip to content

Exercise #1_02 | Flask Dynamic Routes

Genie52 edited this page Jun 12, 2019 · 1 revision

In this exercise we are focusing on routing and variable rules.

To see Routing and Variables in action first review and start 02-Flask-DynamicRoutes-Finish.py from 01 - Flask Basics directory. As you saw in previous exercise this will start Flask Web Server with some nice surprises!

python 02-Flask-DynamicRoutes-Finish.py

Then check what we can see hosted in our Flask web server with the following URLs:

When you are finished do not forget to CTRL + C on your currently running Flask Web Server.

Routing

Modern web applications use meaningful URLs to help users. Users are more likely to like a page and come back if the page uses a meaningful URL they can remember and use to directly visit a page.

Use the route() decorator to bind a function to a URL.

Example:

#this is the URL path we gonna use to access this page! 
# eg. http://localhost:5000/tableauinfo

@app.route('/tableauinfo') 
def tableauinfo():
    return '<h1>Tableau is the Best!</h1>'

Variable Rules

You can add variable sections to a URL by marking sections with <variable_name>. Your function then receives the <variable_name> as a keyword argument.

Example:

# this is a dynamic URL that expects a parameter
# eg. http://localhost:5000/participant/Sophie
@app.route('/participant/<name>')
def participant(name):
    return '<h1>Hello {}, welcome to TCE 19!<h1>'.format(name)

Now its the time to edit our START file. Open 02-Flask-DynamicRoutes-Start.py in Atom and look at the code - you can see we are missing par that will give us routing with variable (variable rules).

Copy/paste or write the following code to the appropriate placeholder:

@app.route('/participant/<name>')
def participant(name):
    return '<h1>Hello {}, welcome to TCE 19!<h1>'.format(name)

Example (after this I believe you got the idea how its going to work in all the exercises):

Save the file and run it! Then check what we can see hosted in our Flask web server with the following URLs: