Skip to main content
Flask provides class-based views as an alternative to function-based views. They allow you to organize related functionality and share common code between views.

View

Base class for all class-based views. Subclass this and override dispatch_request to create a generic view.
from flask.views import View

class Hello(View):
    init_every_request = False

    def dispatch_request(self, name):
        return f"Hello, {name}!"

app.add_url_rule("/hello/<name>", view_func=Hello.as_view("hello"))

Class Attributes

methods
Collection[str] | None
default:"None"
The HTTP methods this view is registered for. Uses the same default (["GET", "HEAD", "OPTIONS"]) as route and add_url_rule by default.
provide_automatic_options
bool | None
default:"None"
Control whether the OPTIONS method is handled automatically. Uses the same default (True) as route and add_url_rule by default.
decorators
list[Callable]
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
init_every_request
bool
default:"True"
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

def dispatch_request(self) -> ResponseReturnValue:
The actual view function behavior. Subclasses must override this and return a valid response. Any variables from the URL rule are passed as keyword arguments. Returns: A valid Flask response value (string, dict, Response object, etc.)

as_view

@classmethod
def as_view(cls, name: str, *class_args: Any, **class_kwargs: Any) -> RouteCallable:
Convert the class into a view function that can be registered for a route. By default, the generated view will create a new instance of the view class for every request and call its 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.
name
str
required
The endpoint name for the route.
class_args
Any
Positional arguments to pass to the view class constructor.
class_kwargs
Any
Keyword arguments to pass to the view class constructor.
Returns: A view function that can be passed to 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 a get method, it will be used to handle GET requests. This can be useful for defining a REST API.
from flask.views import MethodView

class CounterAPI(MethodView):
    def get(self):
        return str(session.get("counter", 0))

    def post(self):
        session["counter"] = session.get("counter", 0) + 1
        return redirect(url_for("counter"))

app.add_url_rule("/counter", view_func=CounterAPI.as_view("counter"))

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 requests
  • post() for POST requests
  • put() for PUT requests
  • patch() for PATCH requests
  • delete() for DELETE requests
  • head() for HEAD requests
  • options() for OPTIONS requests
  • trace() for TRACE requests

Methods

dispatch_request

def dispatch_request(self, **kwargs: Any) -> ResponseReturnValue:
Automatically dispatches the request to the method corresponding to the HTTP method. For example, a GET request will call the get() method. If the request method is HEAD and there’s no handler for it, it will retry with the get() method.
kwargs
Any
URL variables from the route are passed as keyword arguments.
Returns: A valid Flask response value. Raises: AssertionError if the request method is not implemented.

Example: REST API

Here’s a complete example of using MethodView to create a REST API:
from flask import Flask, request, jsonify
from flask.views import MethodView

app = Flask(__name__)

class UserAPI(MethodView):
    def get(self, user_id):
        if user_id is None:
            # Return a list of users
            return jsonify({"users": []})
        else:
            # Return a single user
            return jsonify({"user": user_id})

    def post(self):
        # Create a new user
        data = request.get_json()
        return jsonify({"created": data}), 201

    def delete(self, user_id):
        # Delete a user
        return '', 204

    def put(self, user_id):
        # Update a user
        data = request.get_json()
        return jsonify({"updated": user_id, "data": data})

# Register the view with different rules for list and detail views
user_view = UserAPI.as_view('user_api')
app.add_url_rule('/users/', defaults={'user_id': None},
                 view_func=user_view, methods=['GET'])
app.add_url_rule('/users/', view_func=user_view, methods=['POST'])
app.add_url_rule('/users/<int:user_id>', view_func=user_view,
                 methods=['GET', 'PUT', 'DELETE'])

See Also

Build docs developers (and LLMs) love