@@ -103,33 +103,34 @@ def view(*args, **kwargs):
103
103
104
104
105
105
class MethodViewType (type ):
106
+ """Metaclass for :class:`MethodView` that determines what methods the view
107
+ defines.
108
+ """
109
+
110
+ def __init__ (cls , name , bases , d ):
111
+ super (MethodViewType , cls ).__init__ (name , bases , d )
106
112
107
- def __new__ (cls , name , bases , d ):
108
- rv = type .__new__ (cls , name , bases , d )
109
113
if 'methods' not in d :
110
- methods = set (rv .methods or [])
111
- for key in d :
112
- if key in http_method_funcs :
114
+ methods = set ()
115
+
116
+ for key in http_method_funcs :
117
+ if hasattr (cls , key ):
113
118
methods .add (key .upper ())
114
- # If we have no method at all in there we don't want to
115
- # add a method list. (This is for instance the case for
116
- # the base class or another subclass of a base method view
117
- # that does not introduce new methods).
119
+
120
+ # If we have no method at all in there we don't want to add a
121
+ # method list. This is for instance the case for the base class
122
+ # or another subclass of a base method view that does not introduce
123
+ # new methods.
118
124
if methods :
119
- rv .methods = sorted (methods )
120
- return rv
125
+ cls .methods = methods
121
126
122
127
123
128
class MethodView (with_metaclass (MethodViewType , View )):
124
- """Like a regular class-based view but that dispatches requests to
125
- particular methods. For instance if you implement a method called
126
- :meth:`get` it means it will respond to ``'GET'`` requests and
127
- the :meth:`dispatch_request` implementation will automatically
128
- forward your request to that. Also :attr:`options` is set for you
129
- automatically::
129
+ """A class-based view that dispatches request methods to the corresponding
130
+ class methods. For example, if you implement a ``get`` method, it will be
131
+ used to handle ``GET`` requests. ::
130
132
131
133
class CounterAPI(MethodView):
132
-
133
134
def get(self):
134
135
return session.get('counter', 0)
135
136
@@ -139,11 +140,14 @@ def post(self):
139
140
140
141
app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))
141
142
"""
143
+
142
144
def dispatch_request (self , * args , ** kwargs ):
143
145
meth = getattr (self , request .method .lower (), None )
146
+
144
147
# If the request method is HEAD and we don't have a handler for it
145
148
# retry with GET.
146
149
if meth is None and request .method == 'HEAD' :
147
150
meth = getattr (self , 'get' , None )
151
+
148
152
assert meth is not None , 'Unimplemented method %r' % request .method
149
153
return meth (* args , ** kwargs )
0 commit comments