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

Flask Route Definition API

URL route definition API

Flask provides three ways to define routing rules: the @app.route() decorator, the add_url_rule() method, and direct manipulation of url_map.


URL variable converters

Converter Syntax Matching Rules Python type
string string:name or Any text without a / (default) str
int int:id Positive integer int
float float:value Positive floating-point number float
path path:filepath Any text (including /) str
any Match any value in a list str
uuid uuid:id Standard UUID format str

add_url_rule parameters

Parameters Type Description
rule str The URL rule string, such as "/user/"
endpoint str The endpoint name; the function name is used by default. url_for references the route by this
view_func callable The view function. It can be omitted and stored in the view_functions dictionary later
defaults dict Default values for URL variables. For example, defaults={"page": 1}
subdomain str Subdomain matching. Requires subdomain_matching to be enabled
methods list Allowed HTTP methods. Defaults to ["GET"] (HEAD and OPTIONS are added automatically)
host str Hostname matching. Requires host_matching to be enabled

Trailing slash behavior

Rule Accessing without a / Accessing with a /
@app.route("/projects/") 308 redirect to /projects/ Normal access
@app.route("/about") Normal access 404 Not Found

Default-value routes

Use the defaults parameter to implement optional URL variables:

Example

Two URLs point to the same function; /users/ is equivalent to /users/page/1

@

app.

route

(

"/users/"

,

defaults

=

{

"page"

:

1

}

)

@

app.

route

(

"/users/page/int:page"

)

def

show_users

(

page

)

:

   

return

f

"Showing page {page}"

Accessing /users/ → page=1

Accessing /users/page/3 → page=3

If both a default-value route and a variable route exist, accessing the URL with the default value will be redirected with a 308 to the simplified form.


Custom converters

Example

from

werkzeug.

routing

import

BaseConverter

Define a custom type converter

class

ListConverter

(

BaseConverter

)

:

   

"""Match a comma-separated list, such as /tags/python,flask"""

   

def

to_python

(

self

,

value

)

:

       

return

value.

split

(

","

)

   

def

to_url

(

self

,

values

)

:

       

return

","

.

join

(

values

)

Register with url_map

app.

url_map

.

converters

[

"list"

]

=

ListConverter

Use the custom converter

@

app.

route

(

"/tags/list:tags"

)

def

show_tags

(

tags

)

:

   

tags is a Python list: ["python", "flask", "web"]

   

return

f

"Tags: {', '.join(tags)}"