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

Flask View Function API

Flask View Function API

View functions can have special attributes attached to control routing behavior. These attributes usually do not need to be set manually, but are very useful in certain advanced scenarios.


View function attributes

property Type Default value Description
name str Function name Used as the endpoint name. In a blueprint, the blueprint name is automatically prefixed
methods list None The HTTP methods accepted by the view function. If not specified in add_url_rule, this value is used
required_methods set None HTTP methods that must be added. Even if methods are explicitly specified in add_url_rule, these will be forcibly added
provide_automatic_options bool None Whether to handle OPTIONS requests automatically. Set to False to customize the OPTIONS response

Use Cases

Scenario Attributes used Description
Custom OPTIONS response provide_automatic_options=False Prevent Flask from automatically generating OPTIONS; handled by the view function itself
Setting methods in a decorator methods A decorator can preset the method list of a view function
Forcibly adding methods required_methods Ensure that specific methods are always registered

Code Example

Example

from

flask

import

Flask

,

request

app

=

Flask

(

name

)

Example 1: Custom OPTIONS response

def

custom_endpoint

(

)

:

   

if

request.

method

==

"OPTIONS"

:

       

Return a custom OPTIONS response

       

return

""

,

200

,

{

"Allow"

:

"GET, POST"

}

   

return

"Hello, RUNOOB!"

Disable automatic OPTIONS

custom_endpoint.

provide_automatic_options

=

False

custom_endpoint.

methods

=

[

"GET"

,

"POST"

,

"OPTIONS"

]

app.

add_url_rule

(

"/custom"

,

view_func

=

custom_endpoint

)

Example 2: Define a decorator that automatically sets methods

def

api_view

(

func

)

:

   

"""Custom decorator: Automatically set methods for a view function"""

    func.

methods

=

[

"GET"

,

"POST"

]

   

return

func

@

api_view

def

api_handler

(

)

:

   

return

{

"status"

:

"ok"

}

app.

add_url_rule

(

"/api"

,

view_func

=

api_handler

)

At this point, methods will be read automatically from the function attributes