Skip to content
Browse files

Simplified HEAD handling for method views

  • Loading branch information...
1 parent 7d7d810 commit 32c7e43dda6600828ae9b11111d722ab92fb0594 @mitsuhiko committed
Showing with 42 additions and 1 deletion.
  1. +2 −0 CHANGES
  2. +35 −0 flask/testsuite/views.py
  3. +5 −1 flask/views.py
View
2 CHANGES
@@ -43,6 +43,8 @@ Relase date to be decided, codename to be chosen.
- Fixed an issue where the test client if used with the with statement did not
trigger the execution of the teardown handlers.
- Added finer control over the session cookie parameters.
+- HEAD requests to a method view now automatically dispatch to the `get`
+ method if no handler was implemented.
Version 0.7.3
-------------
View
35 flask/testsuite/views.py
@@ -110,6 +110,41 @@ def dispatch_request(self):
self.assert_equal(rv.headers['X-Parachute'], 'awesome')
self.assert_equal(rv.data, 'Awesome')
+ def test_implicit_head(self):
+ app = flask.Flask(__name__)
+
+ class Index(flask.views.MethodView):
+ def get(self):
+ return flask.Response('Blub', headers={
+ 'X-Method': flask.request.method
+ })
+
+ app.add_url_rule('/', view_func=Index.as_view('index'))
+ c = app.test_client()
+ rv = c.get('/')
+ self.assert_equal(rv.data, 'Blub')
+ self.assert_equal(rv.headers['X-Method'], 'GET')
+ rv = c.head('/')
+ self.assert_equal(rv.data, '')
+ self.assert_equal(rv.headers['X-Method'], 'HEAD')
+
+ def test_explicit_head(self):
+ app = flask.Flask(__name__)
+
+ class Index(flask.views.MethodView):
+ def get(self):
+ return 'GET'
+ def head(self):
+ return flask.Response('', headers={'X-Method': 'HEAD'})
+
+ app.add_url_rule('/', view_func=Index.as_view('index'))
+ c = app.test_client()
+ rv = c.get('/')
+ self.assert_equal(rv.data, 'GET')
+ rv = c.head('/')
+ self.assert_equal(rv.data, '')
+ self.assert_equal(rv.headers['X-Method'], 'HEAD')
+
def suite():
suite = unittest.TestSuite()
View
6 flask/views.py
@@ -143,5 +143,9 @@ def post(self):
def dispatch_request(self, *args, **kwargs):
meth = getattr(self, request.method.lower(), None)
- assert meth is not None, 'Not implemented method'
+ # if the request method is HEAD and we don't have a handler for it
+ # retry with GET
+ if meth is None and request.method == 'HEAD':
+ meth = getattr(self, 'get', None)
+ assert meth is not None, 'Not implemented method %r' % request.method
return meth(*args, **kwargs)

0 comments on commit 32c7e43

Please sign in to comment.
Something went wrong with that request. Please try again.