Flask URL Converters
A URL converter checks the type of a route variable. The int converter takes whole numbers only.
Make the app
This line makes the Flask app. The route below belongs to it.
from flask import Flask
app = Flask(__name__)Add a numbers route
The converters <int:a> and <int:b> take whole numbers. They arrive as numbers, so a + b adds them.
@app.route("/add/<int:a>/<int:b>")
def add(a, b):
return str(a + b)Ask with numbers and with words
The first address adds 3 and 4. The second address sends words where numbers belong, so the answer is a 404 status.
client = app.test_client()
print(client.get("/add/3/4").data.decode())
print(client.get("/add/three/4").status_code)Example
from flask import Flask
app = Flask(__name__)
@app.route("/add/<int:a>/<int:b>")
def add(a, b):
return str(a + b)
client = app.test_client()
print(client.get("/add/3/4").data.decode())
print(client.get("/add/three/4").status_code)Key points
- <int:n> takes whole numbers only.
- The value arrives as a number, not as text.
- <float:x> takes decimal numbers.
- <path:rest> takes several parts, slashes included.
- A wrong type gives a 404 page.
In this example, the route takes two whole numbers. The view adds them and returns the sum as text. The test client asks for 3 + 4 and prints 7. It then asks with a word, and the print shows the 404 status.
Note
A route without a converter takes text.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does /add/three/4 return for the route /add/<int:a>/<int:b>?