Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Flask Routing

Flask Routing

Routing is one of the most core features of a web framework; it determines which URL is handled by which function.

Flask routing is the mechanism in web applications that maps URLs to Python functions.

Flask routing is a core part of Flask applications, used to handle requests to different URLs and delegate request handling to the corresponding view functions.

The following is a detailed explanation of Flask routing, including route definitions, parameters, methods, and rules.


Basic routing

Use the @app.route() decorator to bind a URL path to a view function:

Example

from

flask

import

Flask

app

=

Flask

(

name

)

Bind the root path "/"

@

app.

route

(

"/"

)

def

index

(

)

:

   

return

"This is the homepage"

Bind the "/hello" path

@

app.

route

(

"/hello"

)

def

hello

(

)

:

   

return

"Hello, RUNOOB!"

Different paths correspond to different functions

@

app.

route

(

"/about"

)

def

about

(

)

:

   

return

"About this site"

When visiting http://127.0.0.1:5000/hello, Flask calls the hello() function.

When visiting http://127.0.0.1:5000/about, Flask calls the about() function.


Variable rules

In real applications, URLs usually contain dynamic parts, such as user IDs, article titles, etc.

Flask uses the syntax to define dynamic parts in a URL, and the corresponding argument is automatically passed to the view function.

String variable (default type)

When no type is specified, the variable defaults to a string, matching any character except the slash /:

Example

is a dynamic variable, and Flask passes its value to the view function as a keyword argument

@

app.

route

(

"/user/"

)

def

show_user

(

username

)

:

   

Note: username may contain malicious scripts, so escaping is needed in real production environments

   

return

f

"

User: {username}

"

Test access:

/user/runoob → page shows "User: runoob"

/user/RUNOOB → page shows "User: RUNOOB"

Type converters

Flask has several built-in converters, specified via the syntax:

Converter Description Example URL Match result
string Default, accepts text that does not contain / /user/runoob username = "runoob"
int Positive integer /post/42 post_id = 42
float Positive floating-point number /price/19.99 price = 19.99
path Accept strings containing / /file/a/b/c.txt filepath = "a/b/c.txt"
uuid UUID-formatted string /item/550e8400-e29b-41d4-a716-446655440000 item_id = UUID string

Example

int converter: only numbers can match; /post/abc returns 404

@

app.

route

(

"/post/int:post_id"

)

def

show_post

(

post_id

)

:

   

post_id is of type int, not a string

   

return

f

"

Article #{post_id}

"

path converter: can match paths containing /

@

app.

route

(

"/file/path:filepath"

)

def

show_file

(

filepath

)

:

   

return

f

"

File path: {filepath}

"

float converter: matches floating-point numbers

@

app.

route

(

"/price/float:amount"

)

def

show_price

(

amount

)

:

   

return

f

"

Price: ¥{amount}

"

uuid converter: only accepts standard UUID format

@

app.

route

(

"/item/uuid:item_id"

)

def

show_item

(

item_id

)

:

   

return

f

"

Product ID: {item_id}

"

Converters not only perform type validation, but also automatically convert the matched value to the corresponding Python type. For example what is passed to the view function is int instead of str。


Trailing slash redirect behavior

The / at the end of a URL has a direct effect on route matching behavior, which confuses many beginners.

Example

Rule 1: Ending with / — like a directory

Visiting /projects automatically redirects to /projects/ with a 308

@

app.

route

(

"/projects/"

)

def

projects

(

)

:

   

return

"Project list page"

Rule 2: Not ending with / — like a file

Visiting /about/ returns 404 Not Found

@

app.

route

(

"/about"

)

def

about

(

)

:

   

return

"About Page"

Route Definition Visit /projects Visit /projects/
@app.route("/projects/") 308 redirect to /projects/ Returns normally
@app.route("/about") Returns normally 404 Not Found

This design helps SEO: it ensures that the same content has only one canonical URL, preventing search engines from indexing the same page twice.


URL building—url_for

url_for() is Flask's built-in URL generation function; it generates the corresponding URL from a view function name.

This has many advantages over hardcoding URL strings:

Example

from

flask

import

Flask

,

url_for

app

=

Flask

(

name

)

@

app.

route

(

"/"

)

def

index

(

)

:

   

return

// Add browsing records

@

app.

route

(

"/login"

)

def

login

(

)

:

   

return

"Login page"

@

app.

route

(

"/user/"

)

def

profile

(

username

)

:

   

return

f

"{username}'s personal homepage"

Use test_request_context() to simulate a request context

This way url_for() can generate URLs correctly

with

app.

test_request_context

(

)

:

   

print

(

url_for

(

"index"

)

)

                   

Output /

   

print

(

url_for

(

"login"

)

)

                   

Output /login

   

print

(

url_for

(

"login"

,

next

=

"/"

)

)

         

Output /login?next=%2F

   

print

(

url_for

(

"profile"

,

username

=

"runoob"

)

)

 

Output /user/runoob

The first argument of url_for() is the view function name (note: the function name, not the URL path).

If the URL contains dynamic variables, just pass the corresponding values as keyword arguments.

Extra unknown arguments are automatically appended as a query string.


HTTP methods

By default, routes only respond to GET requests.

The allowed HTTP methods can be specified via the methods parameter:

Example

from

flask

import

Flask

,

request

app

=

Flask

(

name

)

The same URL responds to both GET and POST requests

@

app.

route

(

"/login"

,

methods

=

[

"GET"

,

"POST"

]

)

def

login

(

)

:

   

Determine the current request type via request.method

   

if

request.

method

==

"POST"

:

       

Handle login form submission (executed on a POST request)

        username

=

request.

form

.

get

(

"username"

)

       

return

f

"

Welcome back, {username}!

"

   

else

:

       

Show the login form (executed on a GET request)

       

return

"""
       


           
           
       

        """

Shortcut method decorators

Flask provides shorthand decorators for common HTTP methods to make code clearer:

Example

Equivalent to @app.route("/login", methods=["GET"])

@

app.

get

(

"/login"

)

def

login_form

(

)

:

   

return

"

...
"

Equivalent to @app.route("/login", methods=["POST"])

@

app.

post

(

"/login"

)

def

login_submit

(

)

:

   

return

"Login successful"

Also supports @app.put(), @app.delete(), @app.patch()

@

app.

delete

(

"/post/int:post_id"

)

def

delete_post

(

post_id

)

:

   

API for deleting an article

   

return

f

"Article {post_id} deleted"

Shortcut decorators Equivalent form Typical use
@app.get("/path") @app.route("/path", methods=["GET"]) Get data, display a page
@app.post("/path") @app.route("/path", methods=["POST"]) Create data, submit a form
@app.put("/path") @app.route("/path", methods=["PUT"]) Update data (full replacement)
@app.delete("/path") @app.route("/path", methods=["DELETE"]) Delete data
@app.patch("/path") @app.route("/path", methods=["PATCH"]) Update data (partial update)

Automatically handled: If a route defines the GET method, Flask automatically adds support for the HEAD method. Meanwhile, the OPTIONS method is usually handled automatically as well.


Binding multiple routes at once

The same view function can be bound to multiple routes:

Example

Two different URLs point to the same view function

@

app.

route

(

"/hello"

)

@

app.

route

(

"/hello/"

)

def

greet

(

name

=

None

)

:

   

name has a default value of None; when visiting /hello, name is None

   

if

name

is

None

:

       

return

"

Hello, World!

"

   

return

f

"

Hello, {name}!

"

When visiting /hello, name takes the default value None; when visiting /hello/runoob, name is "runoob".