HTML Templates in Flask

Python
Flask
Web Applications
URL
HTML Templates
Author

Galen Seilis

Published

July 29, 2024

In this post we will not only have dynamic URLs, but start loading HTML templates. In the last post I wrote on Flask I used the factorial function. In this post we’ll take a number and GET/POST different templates depending on whether the input number is a prime number.

To check that a number is prime we can first check whether the candidate is less than 2. For natural numbers the number 2 is the smallest prime.

Note

In the complex numbers, \(\mathbb{C}\), the number 2 is not a “Gaussian prime”. It can be factored:

\[2 = (1 + i) (1 - i)\]

The next criterion is that we only need to check whether there exists a natural number \(k\) such that \(k^2 < n\) and \(k | n\). If such a number \(k\) does not exist, then \(n\) is a prime number.

In this example I prepared two templates:

The directory templates is in the same directory that the Flask application will be run. In example_is_prime.html I put

<h1>The number {{ number }} is a prime!</h1>

and in example_is_not_prime.html I put

<h1>The number {{ number }} is not a prime!</h1>

Note that neither of these files have the usual preamble that you’d find in an index.html file. That’s taken care of behind the scenes. You can also see { number } which specifies a variable name that is expected to come from render_template.

from flask import Flask, render_template

def is_prime(n):
    if n < 2:
        return False
    i = 2
    while i*i <= n:
        if n % i == 0:
            return False
        i += 1
    return True


app = Flask(__name__)

@app.route('/primality/<int:number>')
def display_primarily(number):
    if is_prime(number):
        return render_template('example_is_prime.html', number=number)
    else:
        return render_template('example_is_not_prime.html', number=number)

if __name__ == '__main__':
    app.run(debug=True)

When you run this application you’ll be able to enter various numbers in, and what will be displayed is a sentence telling you whether the number you provided in the URL is a prime number of note.