Flask webserver - dynamic pages

By Martin McBride, 2020-01-22
Tags: template html datetime system
Categories: flask


The main advantage of Flask is that you are using Python to create your web pages. If you need to do something a bit different to a standard static page, you can just code it in Python.

To illustrate this, we will add another page to our site to print out some status information. We will just add some random facts - the current date, the server operating system and the Python version we are using. You can add some more of your own if you like. You might even do something more involved, such as calling the twitter API to fetch your organisations's latest tweets, or scraping a website to get a weather forecast, and including that on your page.

A new HTML template

Since we are presenting structured content (a list of information) rather than just a block of text, we will create a new template with some new tags:

<html>
  <head>
    <link rel="stylesheet" href='/static/main.css' />
  </head>
  <body>
    <h1>{{title}}</h1>
    Date: {{date}}
    Operating system: {{operating_system}}
    Python version: {{python_version}}
  </body>
</html>

We have removed the {{content}} tag, and replaced it with some extra tags, each in its own paragraph. Save this file as status.html in the templates folder.

Changing the Python code

We need some extra includes at the top of the file. These are needed to get the extra information for the status page:

import platform
import sys
import datetime

And, of course, we will need an extra routing function for our page:

@app.route('/status')
def status():
    dt = str(datetime.datetime.now())
    os = platform.system()
    pyver = sys.version
    return render_template('status.html',
                           title='Status',
                           date=dt,
                           operating_system=os,
                           python_version=pyver)

The new routing function has a different route, /status, and a different function name status. We are also using the new template, status.html.

The code first obtains the date and time, operating system name and Python version using standard Python calls. Look them up in the Python documentation to find out more. These values are passed as named parameters into render_template().

You can view the status page by visiting http://127.0.0.1/status with your browser.

The full code for this section can be found on github.

If you found this article useful, you might be interested in the book NumPy Recipes or other books by the same author.

Join the PythonInformer Newsletter

Sign up using this form to receive an email when new content is added:

Popular tags

2d arrays abstract data type alignment and angle animation arc array arrays bar chart bar style behavioural pattern bezier curve built-in function callable object chain circle classes clipping close closure cmyk colour combinations comparison operator comprehension context context manager conversion count creational pattern data science data types decorator design pattern device space dictionary drawing duck typing efficiency ellipse else encryption enumerate fill filter font font style for loop formula function function composition function plot functools game development generativepy tutorial generator geometry gif global variable gradient greyscale higher order function hsl html image image processing imagesurface immutable object in operator index inner function input installing iter iterable iterator itertools join l system lambda function len lerp line line plot line style linear gradient linspace list list comprehension logical operator lru_cache magic method mandelbrot mandelbrot set map marker style matplotlib monad mutability named parameter numeric python numpy object open operator optimisation optional parameter or pandas partial application path pattern permutations pie chart pil pillow polygon pong positional parameter print product programming paradigms programming techniques pure function python standard library radial gradient range recipes rectangle recursion reduce regular polygon repeat rgb rotation roundrect scaling scatter plot scipy sector segment sequence setup shape singleton slice slicing sound spirograph sprite square str stream string stroke structural pattern subpath symmetric encryption template text text metrics tinkerbell fractal transform translation transparency triangle truthy value tuple turtle unpacking user space vectorisation webserver website while loop zip zip_longest