Class-Based Views with MethodView

Class-Based Views with MethodView in Flask: --- Walk into a neighborhood bank branch and you will usually find a single teller window handling the everyday…


The Analogy: A Bank Branch's Single Teller Window

Walk into a neighborhood bank branch and you will usually find a single teller window handling the everyday business of one counter. Behind the glass sits a teller trained in a fixed set of standard procedures, and each procedure is written on its own laminated card in a small stand: one card for taking a deposit, one for paying out a withdrawal, one for reading back a balance. When a customer steps up, the teller does not improvise. They take a clean worksheet from the pad, note the customer's account number on it, and work that single customer's transaction from start to finish on that one fresh sheet.

The customer hands over a slip stamped with exactly one transaction type, and the teller simply pulls the matching card and follows it. A slip stamped DEPOSIT is worked with the deposit card; a slip stamped BALANCE is worked with the balance card. If a customer asks for something the window does not offer -- a wire transfer, say, when no wire card is in the stand -- the teller does not guess or apologize at length; they point to the posted "Services At This Window" sign, which lists exactly the transactions this window handles, and send the customer to the right desk. That posted sign is generated straight from the set of cards in the stand, so it is always accurate.

The same teller training is not tied to one window. The branch can open a second window during the lunch rush and staff it with a teller holding the identical stack of procedure cards, the only difference being which account book that window is bound to when it opens for the day. One window may be assigned the personal-accounts book and another the business-accounts book, yet both tellers follow the very same deposit, withdrawal, and balance procedures. The procedure is defined once; the binding to a particular book happens when the window is opened.

The system holds together only because every customer gets a fresh worksheet. The failure begins the day a hurried teller bolts a single scratch tray to the counter and starts jotting the running total there instead of on each customer's own sheet, reasoning that it saves reaching for the pad. The tray is never cleared between customers. The next person to step up glances down and sees the previous customer's balance staring back, and worse, a figure they add is quietly combined with a stranger's. Nothing in the window looks broken -- the cards are right, the sign is right -- but a scrap of paper meant to be private has become shared property, and one customer's money is now tangled with another's.


Syntax or Core Structure

A MethodView is a class whose methods are named after HTTP verbs. You subclass flask.views.MethodView, define get, post, delete, and so on, then register it with add_url_rule by calling as_view to produce a view function. On each request Flask reads the HTTP method, creates a brand-new instance of your class, and dispatches to the matching lowercase method.

from flask import Flask
from flask.views import MethodView

app = Flask(__name__)


class GreetView(MethodView):
    def get(self):
        return "hello from GET"

    def post(self):
        return "hello from POST"


app.add_url_rule("/greet", view_func=GreetView.as_view("greet"))

client = app.test_client()
print(client.get("/greet").get_data(as_text=True))
print(client.post("/greet").get_data(as_text=True))
print(client.put("/greet").status_code)

Output:

hello from GET
hello from POST
405

The get method answers GET and post answers POST. Because the class defines no put method, Flask automatically refuses PUT with 405 Method Not Allowed -- you never write that rejection by hand. The single string passed to as_view ("greet") becomes the endpoint name that url_for and the URL map use.


Technical Depth: Registering Classes, Method Dispatch, and Reuse

Three mechanics make class-based views worth the extra structure: how as_view turns a class into a registered view function, how Flask decides which method handles a request, and how one class body can serve several resources.

Registering a class as a view

as_view(name, *args, **kwargs) builds the view function. Its first argument is the endpoint name; any further arguments are stored and passed to your class constructor on every request. That lets one class serve two resources -- each registration binds a different constructor argument, exactly like staffing two windows from the same training but a different account book.

from flask import Flask
from flask.views import MethodView

app = Flask(__name__)


class ListView(MethodView):
    def __init__(self, model):
        self.model = model

    def get(self):
        return f"listing {self.model}"


app.add_url_rule("/users", view_func=ListView.as_view("users", "user"))
app.add_url_rule("/orders", view_func=ListView.as_view("orders", "order"))

client = app.test_client()
print(client.get("/users").get_data(as_text=True))
print(client.get("/orders").get_data(as_text=True))

Output:

listing user
listing order

Each request builds a fresh ListView("user") or ListView("order"), so the model set in __init__ is genuine per-request instance state and never bleeds between the two endpoints.

Automatic method handling

You define only the methods you support. Flask fills in the rest: it answers OPTIONS with an Allow header listing your methods, adds HEAD whenever you define get, and returns 405 Method Not Allowed for any verb you did not implement. The posted "services" sign writes itself.

Request methodWhat MethodView does
A verb you definedCalls the matching lowercase method
HEAD (with get defined)Runs get, then strips the body
OPTIONSReturns 200 with an Allow header, no handler needed
A verb you did not defineReturns 405 Method Not Allowed
from flask import Flask
from flask.views import MethodView

app = Flask(__name__)


class ArticleView(MethodView):
    def get(self, aid):
        return f"article {aid}"

    def delete(self, aid):
        return f"deleted {aid}"


app.add_url_rule("/articles/<int:aid>", view_func=ArticleView.as_view("article"))

client = app.test_client()
r = client.options("/articles/5")
print("options status:", r.status_code)
print("allow:", sorted(r.headers["Allow"].replace(" ", "").split(",")))
print("put status:", client.put("/articles/5").status_code)

Output:

options status: 200
allow: ['DELETE', 'GET', 'HEAD', 'OPTIONS']
put status: 405

Note that HEAD and OPTIONS appear in Allow even though the class never mentions them, and PUT is rejected without a line of your code. The URL converter <int:aid> is passed straight into each method as the aid argument.

Class-based views versus functions

Neither style is universally better. Function views are the shortest path for a single endpoint; class-based views earn their place when one URL carries several methods, when several resources share behavior, or when a base class should enforce a common policy such as authentication.

ConcernFunction viewMethodView
One method per URLIdeal, least ceremonyOverkill
Many methods per URLif request.method branchingOne method each, auto dispatch
Sharing logic across resourcesCopy or helper functionsSubclass a common base
405 and OPTIONS handlingManual, easy to forgetProvided automatically
Per-request stateLocal variablesAttributes on a fresh instance

A common pattern is a base MethodView that defines shared setup -- decorators, a get_object helper, permission checks -- which concrete views subclass. The decorators class attribute is one legitimate use of a class attribute: Flask reads it once at registration to wrap the view, and it is configuration, not per-request data. The danger is mistaking that pattern for permission to store request or user data on the class, which the Real World example below makes painfully concrete.


Real World Example: A "Recently Viewed" List That Everyone Shares

A shopping site wants a "recently viewed" endpoint. A developer reaches for MethodView -- post records a product, get reads the list back -- and stores the list on the class so it persists between requests. It does persist. That is the whole problem.

from flask import Flask
from flask.views import MethodView

app = Flask(__name__)


class RecentlyViewed(MethodView):
    seen = []  # meant as per-user history; actually shared by everyone

    def post(self, product):
        self.seen.append(product)
        return {"you_added": product}

    def get(self):
        return {"recent": list(self.seen)}


app.add_url_rule("/recent", view_func=RecentlyViewed.as_view("recent_list"))
app.add_url_rule(
    "/recent/<product>", view_func=RecentlyViewed.as_view("recent_add")
)

client = app.test_client()
# Customer A views a product from one connection...
print("A adds:", client.post("/recent/laptop").get_json())
# ...and Customer B, a different person, checks their own list.
print("B sees:", client.get("/recent").get_json())

Output:

A adds: {'you_added': 'laptop'}
B sees: {'recent': ['laptop']}

Customer A, on one connection, posts laptop and gets back a tidy confirmation. Customer B -- a different person on a different session, who has viewed nothing -- asks for their recently viewed list and is handed A's laptop. The feature works exactly as written and leaks one shopper's browsing history to the next.

The list survives between requests because seen = [] is evaluated once, when the class is defined, and lives on the class object for the whole process lifetime. self.seen.append(product) looks up seen on the instance, fails to find it there, falls through to the class, and mutates that single shared list in place. Every instance of RecentlyViewed, across every request and every user, reads and writes the very same list.

The irony is that Flask already gave the developer the isolation they wanted. Each request builds a brand-new RecentlyViewed instance, so anything assigned to self inside a method -- a value from __init__, a self.model -- is safely per-request. The bug is not that instances are reused; they are not. The bug is reaching past the fresh instance to a value bolted onto the class, the scratch tray screwed to the counter.

The genuine design flaw is storing per-user state in a mutable class attribute. It is invisible in a single-user test, corrupts data the moment two users overlap, and doubles as an unbounded memory leak. Per-user data belongs in the session or a database keyed by the authenticated user, never on the class or the instance; class attributes should hold only configuration such as decorators. A bug shaped exactly like this can serve requests for months before anyone notices, because it only misbehaves under the concurrency that staging never sees.


Common Mistakes

  1. Storing per-user or per-request data on the class. A mutable class attribute like seen = [] is shared by every request and every user, leaking one person's data to the next and growing without bound.
  1. Assuming instance attributes survive between requests. Flask builds a fresh instance per request, so a value set on self in one request is gone in the next -- the exact opposite trap to storing state on the class.
  1. Registering the class instead of its as_view result. view_func must be MyView.as_view("name"); passing the class object itself does not produce a working view.
  1. Reusing the same endpoint name for two as_view calls. Endpoint names must be unique across the app, or registration errors or one route silently overwrites the other.
  1. Capitalizing method names or inventing verbs. Only lowercase HTTP method names such as get, post, put, patch, and delete are dispatched; a method named Get or fetch is never called.
  1. Hand-writing OPTIONS and 405 responses. MethodView supplies both automatically from the methods you defined; manual versions drift out of sync with the real Allow header.
  1. Decorating a single method and expecting it to apply. Per-method decorators on a MethodView are not honored the way you expect; use the decorators class attribute (which wraps every method) or apply the logic inside the method.
  1. Doing expensive work in __init__. The constructor runs on every request, so opening files, building clients, or querying there repeats that cost per call; keep construction cheap.
  1. Reusing one subclass for several resources without distinct as_view arguments. If both routes call as_view with the same constructor arguments, the two endpoints behave identically and the reuse buys nothing.

Best Practices

  • Reach for MethodView when one URL genuinely carries several methods. A resource that supports GET, POST, and DELETE is where the class form pays for itself over a single function with if request.method branching.
  • Keep all mutable state per-request or external. Use local variables and self inside methods for request-scoped data, and the session or a database for anything that must outlive the request; reserve class attributes for configuration.
  • Vary behavior through as_view constructor arguments. Passing a model, a template name, or a service into __init__ lets one class body serve many resources without copy-paste.
  • Factor cross-cutting concerns into a shared base class. A base MethodView with a get_object helper or a permission check keeps concrete views small and consistent.
  • Use the decorators class attribute for wrapping every method. Listing login_required or a rate limiter in decorators applies it uniformly and is the one class attribute meant to be shared.
  • Let Flask own OPTIONS, HEAD, and 405. Define only the verbs you support and trust the automatic handling for the rest, so the Allow header can never fall out of sync.
  • Give every registration a clear, unique endpoint name and link with url_for. Descriptive names make the URL map readable and keep links robust when paths change.
  • Do not over-engineer single-method endpoints. If a URL only ever answers GET, a plain function view is shorter and clearer than a one-method class.

Practice Exercises

  1. A full resource class. Write a MethodView for /notes with get, post, and delete, register it with as_view, then use the test client to confirm the Allow header lists exactly those verbs (plus HEAD and OPTIONS) and that PUT returns 405.
  1. Reproduce and fix the leak. Recreate the shared class-attribute bug from the Real World example, prove with two separate client requests that one sees the other's data, then move the state into the session (or a dict keyed by a user id) and show the two clients are now isolated.
  1. One class, two resources. Give a MethodView an __init__ that takes a resource name, register it at /books and /authors with different as_view arguments, and demonstrate through both endpoints that the per-request self value stays independent.
  1. A base class with shared decorators. Define a base MethodView whose decorators class attribute contains a small logging or counting wrapper, subclass it for a concrete view, and show through the test client that the wrapper runs for both get and post without being listed on either method.