Skip to content
Myr

use __init_subclass__ instead of metaclass for MethodView

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Lord · committed by David Lord · parent bab5a65 · Browse files · 1 file+19 added−29 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+19 added−29 removed

  • other:+19 added−29 removed

1 file+19 added−29 removed

modified:src/flask/views.py+19 added-29 removed
43 unmodified lines
4445 #: The methods this view is registered for. Uses the same default46 #: (``["GET", "HEAD", "OPTIONS"]``) as ``route`` and47 #: ``add_url_rule`` by default.48 methods: t.ClassVar[t.Optional[t.List[str]]] = None48 methods: t.ClassVar[t.Optional[t.Collection[str]]] = None4950 #: Control whether the ``OPTIONS`` method is handled automatically.51 #: Uses the same default (``True``) as ``route`` and52 #: ``add_url_rule`` by default.
78 unmodified lines
131 view.provide_automatic_options = cls.provide_automatic_options # type: ignore132 return view133134135class MethodViewType(type):136 """Metaclass for :class:`MethodView` that determines what methods the view137 defines.138 """139140 def __init__(cls, name, bases, d):141 super().__init__(name, bases, d)142143 if "methods" not in d:144 methods = set()145146 for base in bases:147 if getattr(base, "methods", None):148 methods.update(base.methods)149150 for key in http_method_funcs:151 if hasattr(cls, key):152 methods.add(key.upper())153154 # If we have no method at all in there we don't want to add a155 # method list. This is for instance the case for the base class156 # or another subclass of a base method view that does not introduce157 # new methods.158 if methods:159 cls.methods = methods160161162class MethodView(View, metaclass=MethodViewType):135class MethodView(View):136 """Dispatches request methods to the corresponding instance methods.137 For example, if you implement a ``get`` method, it will be used to138 handle ``GET`` requests.139
18 unmodified lines
158 "/counter", view_func=CounterAPI.as_view("counter")159 )160 """161162 def __init_subclass__(cls, **kwargs: t.Any) -> None:163 super().__init_subclass__(**kwargs)164165 if "methods" not in cls.__dict__:166 methods = set()167168 for base in cls.__bases__:169 if getattr(base, "methods", None):170 methods.update(base.methods) # type: ignore[attr-defined]171172 for key in http_method_funcs:173 if hasattr(cls, key):174 methods.add(key.upper())175176 if methods:177 cls.methods = methods178179 def dispatch_request(self, **kwargs: t.Any) -> ft.ResponseReturnValue:180 meth = getattr(self, request.method.lower(), None)181182 # If the request method is HEAD and we don't have a handler for it
6 unmodified lines