Modern web apps use a technique named routing. This helps the user remember the URLs. For instance, instead of having /booking.php they see /booking/. Instead of /account.asp?id=1234/ they’d see /account/1234/.
Related course: Python Flask: Create Web Apps with Flask
Routes
flask route example
Routes in Flask are mapped to Python functions. You have already created one route, the ‘/‘ route:
|
The route() decorator, @app.route()
, binds a URL to a function.
If you want the route /hello, you can bind it to the hello_world() function like this:
|
The output of the function hello_world() is shown in your browser.
flask route params
Parameters can be used when creating routes. A parameter can be a string (text) like this: /product/cookie
.
That would have this route and function:
|
So you can pass parameters to your Flask route, can you pass numbers?
The example here creates the route /sale/<transaction_id>
, where transaction_id is a number.
|
flask route multiple arguments
If you want a flask route with multiple parameters that’s possible. For the route /create/<first_name>/<last_name>
you can do this:
|
flask route post
Flask suports HTTP POST requests. If you are unfamiliar with this, I recommend this course: Create apps with Flask.
Create a template named login.html
1 | <html> |
The code below supports both type of HTTP requests.
1 | from flask import Flask |
If you get an error like this, your routing is wrong:
werkzeug.routing.BuildError
werkzeug.routing.BuildError: Could not build url for endpoint 'dashboard'. Did you forget to specify values ['name']?