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.
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:
templates/example_is_prime.html
templates/example_is_not_prime.html
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
= 2
i while i*i <= n:
if n % i == 0:
return False
+= 1
i return True
= Flask(__name__)
app
@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__':
=True) app.run(debug
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.