Flask Class-Based Views API

Flask provides two kinds of class-based views, allowing you to organize view logic in an object-oriented way.

ViewIs the most basic class-based view,MethodViewAutomatically dispatches according to HTTP methods.


View base class

Attributes/Methods Description
methods Class attribute, the list of HTTP methods accepted by the view. Default None (uses the default value of add_url_rule)
decorators Class attribute, the list of decorators. Applied in order to the generated view function
init_every_request Class attribute, bool. When True (default), a new instance is created for each request; when False, a single instance is reused.
provide_automatic_options Class attribute, whether to automatically implement OPTIONS. Default None (uses the app configuration)
dispatch_request(**kwargs) Core method, must be overridden. kwargs are the URL variables
as_view(name, *class_args, **class_kwargs) Class method, creates a view function that can be used in add_url_rule

MethodView class

Inherits from View, automatically dispatches to the corresponding instance method according to HTTP method.

Method Naming Conventions Description
get(self, **kwargs) Handles GET requests
post(self, **kwargs) Handles POST requests
put(self, **kwargs) Handles PUT requests
delete(self, **kwargs) Handles DELETE requests
patch(self, **kwargs) Handles PATCH requests

After defining these methods,methodsThe attribute is automatically set based on the defined methods.


View vs MethodView

Features View MethodView
Dispatch method A single dispatch_request handles all methods Automatically dispatches by method name (get→GET, etc.)
Applicable scenarios Generic views, template rendering RESTful API

Code Examples

Example

from flask import Flask, request, session, redirect, url_for
from flask.views import View, MethodView

app = Flask(__name__)

# Basic View: single dispatch_request
class HelloView(View):
    def dispatch_request(self, name):
        return f"<h1>Hello, {name}!</h1>"

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

# MethodView:RESTful API
class PostAPI(MethodView):
    # Custom initialization (called on every request)
    def __init__(self):
        self.db = get_database_connection()

    def get(self, post_id=None):
        if post_id is None:
            posts = self.db.query_all_posts()
            return {"posts": posts}
        return self.db.get_post(post_id)

    def post(self):
        data = request.json
        post_id = self.db.create_post(data["title"], data["body"])
        return {"id": post_id}, 201

    def delete(self, post_id):
        self.db.delete_post(post_id)
        return {"message": "deleted"}

# Registration: the same view function handles multiple methods
post_view = PostAPI.as_view("post_api")
app.add_url_rule("/api/posts", defaults={"post_id": None},
                 view_func=post_view, methods=["GET", "POST"])
app.add_url_rule("/api/posts/<int:post_id>",
                 view_func=post_view, methods=["GET", "DELETE"])
other extensions