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/.
Practice now: Test your Python skills with interactive challenges
Routes
flask route example
Routes in Flask are mapped to Python functions. You have already created one route, the '/' route:
@app.route('/')
def index():
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:
@app.route('/hello')
def hello_world():
return "hello world"
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:
@app.route('/product/<name>')
def get_product(name):
return "The product is " + str(name)
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.
@app.route('/sale/<transaction_id>')
def get_sale(transaction_id=0):
return "The transaction is "+str(transaction_id)
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:
@app.route('/create/<first_name>/<last_name>')
def create(first_name=None, last_name=None):
return 'Hello ' + first_name + ',' + last_name
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
<html>
<body>
<form action = "http://localhost:5000/login" method = "post">
<p>Username:</p>
<p><input type = "text" name = "name" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>
</body>
</html>
The code below supports both type of HTTP requests.
from flask import Flask
from flask import render_template
from flask import request
from flask import Flask, redirect, url_for, request
app = Flask(__name__)
@app.route('/dashboard/<name>')
def dashboard(name):
return 'welcome %s' % name
@app.route('/login',methods = ['POST', 'GET'])
def login():
if request.method == 'POST':
user = request.form['name']
return redirect(url_for('dashboard',name = user))
else:
user = request.args.get('name')
return render_template('login.html')
if __name__ == '__main__':
app.run(debug = True)
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']?