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
Provenance
- Commit
45174bf- Tree
7af57bc- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
bab5a65
1 file changed+19 added−29 removed
modified:src/flask/views.py+19 added-29 removed
43 unmodified lines44 45 #: 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]]] = None49 50 #: Control whether the ``OPTIONS`` method is handled automatically.51 #: Uses the same default (``True``) as ``route`` and52 #: ``add_url_rule`` by default.78 unmodified lines131 view.provide_automatic_options = cls.provide_automatic_options # type: ignore132 return view133 134 135-class MethodViewType(type):136- """Metaclass for :class:`MethodView` that determines what methods the view137- defines.138- """139-140- def __init__(cls, name, bases, d):141- super().__init__(name, bases, d)142-143- if "methods" not in d:144- methods = set()145-146- for base in bases:147- if getattr(base, "methods", None):148- methods.update(base.methods)149-150- for key in http_method_funcs:151- if hasattr(cls, key):152- methods.add(key.upper())153-154- # 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 = methods160-161-162-class MethodView(View, metaclass=MethodViewType):135+class 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 lines158 "/counter", view_func=CounterAPI.as_view("counter")159 )160 """161 162+ def __init_subclass__(cls, **kwargs: t.Any) -> None:163+ super().__init_subclass__(**kwargs)164+165+ if "methods" not in cls.__dict__:166+ methods = set()167+168+ for base in cls.__bases__:169+ if getattr(base, "methods", None):170+ methods.update(base.methods) # type: ignore[attr-defined]171+172+ for key in http_method_funcs:173+ if hasattr(cls, key):174+ methods.add(key.upper())175+176+ if methods:177+ cls.methods = methods178+179 def dispatch_request(self, **kwargs: t.Any) -> ft.ResponseReturnValue:180 meth = getattr(self, request.method.lower(), None)181 182 # If the request method is HEAD and we don't have a handler for it6 unmodified lines