DEV Community

Emma Donery
Emma Donery

Posted on

Python Flask App Routing

Alt text of image

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"


Enter fullscreen mode Exit fullscreen mode

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!"


Enter fullscreen mode Exit fullscreen mode

Defining Routes & Views

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.

URL Route Registrations

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.

Route HTTP Methods

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


Enter fullscreen mode Exit fullscreen mode

Dynamic Routes & Variable Rules

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


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

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

Types of View Responses - common ways a route will conclude

  • Rendering Page Templates
  • Making a Response Object
  • Redirecting Users Between Views

NOTE:Rules for dealing with trailing slashes

  1. 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.

  2. 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.

Top comments (2)

Collapse
 
socr102 profile image
Eric

Good I hope you are doing well
And I think it is a beginner level knowledge of FLASK
Anyway thank you for your post
It will be used useful for beginner developer for FLASK
Can you make a post how to connect the MySQL DB in flask
I'll be waitng for your next post
thank you
best

Collapse
 
emma_donery profile image
Emma Donery

thank you @Elina for your comment! sure i will make that request my next article. Be sure to stay tuned. By the end of the week i will have made the post