16
Python Flask App Routing
Clients such as web browsers send requests to the web server, which in turn sends them to the Flask application instance.
The Flask application instance needs to know what code it needs to run for each URL requested, so it keeps a mapping of URLs to Python functions.
The most convenient way to define a route in a Flask application is through the app.route decorator exposed by the application instance.
A route is the association between a URL and the function that handles it
App routing is used to map the specific URL with the associated function that is intended to perform some task.
The routing technique helps a user remember application URLs and is useful to access the desired page directly without having to navigate from the home page.
The route() decorator in Flask is used to bind URL to a function.
The example defines a route listening at the root our app and executes a view function called index():
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return "I love Flask"
Tip: You can handle multiple routes with a single function by stacking additional route decorators above any route. in simple terms, you can also define multiple rules for the same function. However, they have to be unique.
Example:
from flask import Flask
app = Flask(__name__)
@app.route("/")
@app.route("/home")
@app.route("/index")
def Index():
return "I love Flask!"
Routes - refer to URL patterns of an app
Views - refer to the content to be served at these URLs, whether that be a web page, an API response, etc.
Generally there are three ways to define rules for the routing system:
You can use the flask.Flask.route() decorator.
You can use the flask.Flask.add_url_rule() function.
You can directly access the underlying Werkzeug routing system which is exposed as flask.Flask.url_map.
Flask supports the common HTTP methods, including GET, POST, PUT, PATCH, DELETE
- GET - Used to fetch the specified resource
- POST - Used to create new data at the specified resource
- PUT - Used to create new data or replace existing data at the specified resource
- PATCH - Used to create new data or update/modify existing data at the specified resource
- DELETE - Used to delete existing data at the specified resource
By default, routes only respond to GET requests. You can change this behavior by supplying the methods argument to the route() decorator.
Example
from flask import Flask
app = Flask(__name__)
@app.route("/users", methods=['GET', 'POST', 'PUT'])
def users():
pass
Variable parts in the route can be specified by marking sections with enaling routes to be dynamically generated.
Variable parts are passed to the view function as keyword arguments.
@app.route('/user/<username>')
def user(username):
#... statement(s)
pass
Variables can be type-checked by adding a colon, followed by the data type constraint.
Example
@app.route('/user/<int:id>')
def user(id):
#... statement(s)
pass
Routes can accept the following variable types:
- string: - Accepts any text without a slash (the default).
- int: - Accepts integers.
- float: - Accepts numerical values containing decimal points.
- path: - like a string, but accepts slashes
- any - matches one of the items provided
- uuid - accepts UUID strings
- Rendering Page Templates
- Making a Response Object
- Redirecting Users Between Views
NOTE:Rules for dealing with trailing slashes
If a rule ends with a slash and is requested without a slash by the user, the user is automatically redirected to the same page with a trailing slash attached.
If a rule does not end with a trailing slash and the user requests the page with a trailing slash, a 404 not found is raised.
16