Intro to Flask Part 2

Dynamic Routes

@app.route('/hello/<name>)
def hello(name):
    return f'Hello {name}

Returning HTML from Flask

You can either return HTML as a string like so:

@app.route('/hello')
def hello_world():
    return """
<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <h1>Hello there.</h1>
    <p>Isn't this lovely!</p>
  </body>
</html>
"""

or use a template.

Serving Dynamic Templates & Static Files

Create static and templates directories so the project directory looks like so:

.
├── app.py
├── static
│   ├── css
│   ├── img
│   └── js
└── templates

Rendering a Template

Flask will automatically look for template files in templates.

Flask uses the Jinja templating engine.

To render a Jinja template, first import the render_template function

from flask import Flask, render_template

Then instead of returning a string in the route handler, return the result of calling render_template('{templatename}.html').

app.py

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

templates/index.html

<ul>
  <li><a href="/hello/bon">bon</a></li>
  <li><a href="/hello/brendan">brendan</a></li>
  <li><a href="/hello/dave">dave</a></li>
  <li><a href="/hello/jason">jason</a></li>
  <li><a href="/hello/jeremy">jeremy</a></li>
  <li><a href="/hello/justin">justin</a></li>
  <li><a href="/hello/michael">michael</a></li>
  <li><a href="/hello/mun">mun</a></li>
  <li><a href="/hello/renata">renata</a></li>
  <li><a href="/hello/shiam">shiam</a></li>
  <li><a href="/hello/tania">tania</a></li>
  <li><a href="/hello/tristram">tristram</a></li>
  <li><a href="/hello/xin">xin</a></li>
  <li><a href="/hello/yuki">yuki</a></li>
</ul>

Adding a Stylesheet

Like templates, Flask will automatically look for and and serve static files in static. So you just have to create your stylesheet file and include it in the template.

<link href="/static/css/styles.css" rel="stylesheet">

Adding Images

Add any image in the static directory (preferably in the img directory but you do you) and flask will serve it at /static/PATH_TO_IMAGE.

<img src="/static/img/dog.jpg" alt="Good Boy" />

Passing Data to Templates

app.py

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

templates/hello.html

<h1>Hello {{ person }}!</h1>
<p>Have you caught up with homework?</p>

Last updated