View
Base class for all class-based views. Subclass this and overridedispatch_request to create a generic view.
Class Attributes
The HTTP methods this view is registered for. Uses the same default (
["GET", "HEAD", "OPTIONS"]) as route and add_url_rule by default.Control whether the
OPTIONS method is handled automatically. Uses the same default (True) as route and add_url_rule by default.A list of decorators to apply, in order, to the generated view function. Remember that
@decorator syntax is applied bottom to top, so the first decorator in the list would be the bottom decorator.Added in version 0.8
Create a new instance of this view class for every request by default. If a view subclass sets this to
False, the same instance is used for every request.A single instance is more efficient, especially if complex setup is done during init. However, storing data on self is no longer safe across requests, and flask.g should be used instead.Added in version 2.2
Methods
dispatch_request
as_view
dispatch_request method. If the view class sets init_every_request to False, the same instance will be used for every request.
Except for name, all other arguments passed to this method are forwarded to the view class __init__ method.
The endpoint name for the route.
Positional arguments to pass to the view class constructor.
Keyword arguments to pass to the view class constructor.
add_url_rule.
Changed in version 2.2: Added the
init_every_request class attribute.MethodView
Dispatches request methods to the corresponding instance methods. For example, if you implement aget method, it will be used to handle GET requests.
This can be useful for defining a REST API.
Automatic Method Detection
methods is automatically set based on the methods defined on the class. The view will look for methods named after HTTP methods:
get()for GET requestspost()for POST requestsput()for PUT requestspatch()for PATCH requestsdelete()for DELETE requestshead()for HEAD requestsoptions()for OPTIONS requeststrace()for TRACE requests
Methods
dispatch_request
get() method.
If the request method is HEAD and there’s no handler for it, it will retry with the get() method.
URL variables from the route are passed as keyword arguments.
Example: REST API
Here’s a complete example of using MethodView to create a REST API:See Also
- Views documentation - Detailed guide on using class-based views
- URL Routing - How to register views with routes
