Categories
Flask

Python Web Development with Flask — Routes and Templates

Spread the love

Flask is a simple web framework written in Python.

In this article, we’ll look at how to develop simple Python web apps with Flask.

Unique URLs / Redirection Behavior

Adding a trailing slash to the URL will get us to access to the URL with our without a trailing slash.

For example, if we write:

from flask import Flask
app = Flask(__name__)

@app.route('/foo/')
def projects():
    return 'The foo page'

@app.route('/bar')
def about():
    return 'The bar page'

We only see ‘The bar page’ when we go to http://localhost:5000/bar.

On the other hand, if we go to http://localhost:5000/foo or http://localhost:5000/foo/, we see ‘The foo page’.

URL Building

We can use the url_for function to show the full URL of each route.

For example, we can write:

from flask import Flask, url_for
from markupsafe import escape

app = Flask(__name__)

@app.route('/')
def index():
    return 'index'

@app.route('/login')
def login():
    return 'login'

@app.route('/user/<username>')
def profile(username):
    return '{}'s profile'.format(escape(username))

with app.test_request_context():
    print(url_for('index'))
    print(url_for('login'))
    print(url_for('login', next='/'))
    print(url_for('profile', username='Jane Smith'))

Then in the with block, we print the full paths created from the routes.

We see:

/
/login
/login?next=%2F
/user/Jane%20Smith

url_for('index') returns ‘/‘.

url_for(‘login’) returns '/login' .

url_for(‘login’, next=’/’) returns ‘/login?next=%2F’ .

And url_for(‘profile’, username=’Jane Smith’) returns /user/Jane%20Smith .

We just pass in the function name into url_for as a string, and we get back the URL constructed from it.

HTTP Methods

A route function can take requests made with different HTTP methods.

We can restrict this with the methods parameter we pass into @app.route .

For example, we can write:

from flask import request, Flask
app = Flask(__name__)

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        return 'logged in'
    else:
        return 'login form'

We set the methods parameter to the [‘GET’, ‘POST’] to restrict the function to only accept GET and POST requests.

Then we can check the request method with the request.method property.

So if we make a POST request to http://127.0.0.1:5000/login, we get ‘logged in‘ returned.

And if we make a GET request to the same URL, we get ‘login form‘ returned.

Static Files

We can serve static files with Flask.

To do that, we write:

app.py

from flask import Flask, url_for
app = Flask(__name__)

@app.route('/')
def hello():
    return 'hello world'

with app.test_request_context():
    print(url_for('static', filename='style.css'))

static/style.css

body {
    font-weight: bold;
}

We print the path to the style.css static file in the static folder with the url_for function.

When we go to http://localhost:5000/static/style.css in the browser, we should see:

body {
    font-weight: bold;
}

displayed.

Rendering Templates

To render HTML output, we‘ve to render the content in a template.

To do that, we can use tyhe render_template function by writing:

app.py

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
    return render_template('hello.html', name=name)

templates/hello.html

<!doctype html>
<title>Hello from Flask</title>
{% if name %}
  <h1>Hello {{ name }}!</h1>
{% else %}
  <h1>Hello, World!</h1>
{% endif %}

We added a route that optionally takes the name parameter.

Then we call render_template with the path of the template in the templates folder.

Then we pass the variables we want to render into the subsequent arguments.

In hello.html , we check if the name variable is present, if it is, then we display the first message with the name ‘s value.

If we go to http://localhost:5000/hello/james, we see Hello james! displayed.

Otherwise, if we go to http://localhost:5000/hello, we see Hello, world.

Conclusion

We add static files and render templates with Flask.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *