Building a Python Flask application — Tutorial 03

Sashini Hettiarachchi
3 min readDec 30, 2018

Hi all, welcome to the third tutorial of “Building a Python Flask application” tutorial series. In this tutorial, I will explain how to do the Routing.

In a simple term, Routing is, giving a specific URL for User Interfaces(web pages).

As an example:

Home page : Localhost:5000/home

Login Page : Localhost:5000/login

Let’s learn how it’s doing using the Flask

We learnt about the route decorator in the previous tutorial.

If we want to route specific URL, it should be put in route decorator

  • URL: localhost:5000/
@app.route('/')
def index():
return 'Index Page'
  • URL: localhost:5000/hello
@app.route('/hello')
def hello_world():
return 'Hello, World'

If you want to keep parts of the URL dynamic and attach multiple rules to a function.

Step 1: Add the variable name to the route decorator

@app.route('/user/<variable_name>')

Step 2: Add the variable name as the function keyword argument

def function_name(variable_name):

Example:

from flask import Flask
app = Flask(__name__)
@app
.route('/user/<username>')
def user_details(username):
return 'User name is %s' % username

If you want to convert the type of the variable

Step 1: Add the variable name and converter type to the route decorator

@app.route(‘/user/<converter:variable_name>’)

Step 2: Add the variable name as the function keyword argument

def function_name(variable_name):

Example:

from flask import Flask
app = Flask(__name__)
@app
.route('/user/<str: username>')
def user_details(username):
return 'User name is %s' % username

Converter types:

http://flask.pocoo.org/docs/1.0/quickstart/

Well, You learnt about routing a flask application.

Let’s learn about rendering HTML templates using Flask application.

You can implement an HTML page as a Jinja2 template because Flask configures the Jinja2 template engine automatically.

Step 1: Write a simple HTML file (Jinja2 template) which you want to render.(more about jinja2)

<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <title>Hello World</title>  </head>  <body>    <h1>Hello World</h1>  </body></html>

Step 2: Create a “templates” folder for saving templates inside project folder.

Step 3: Save the template as “hello.html”(you can use any name)

Step 4: Modify the app.py

  • import render_template
  • return render_template(‘hello.html’)
from flask import Flaskfrom flask import render_templateapp = Flask(__name__)
@app.route('/')def hello_world(): return render_template('hello.html')if __name__ == '__main__': app.run()

Well, now you know how to do the routing and rendering a template in a flask application.

In the next tutorial, Teach you about the database connecting of a flask application.

Good Luck!

Bye.

For the previous tutorials:

First tutorial

Second tutorial

--

--