Skip to content
Browse files

Implement support for X-HTTP-Method-Override in flask.views.MethodView.

When an incoming request contains the X-HTTP-Method-Override header, the
value of that header is used as the view method to be executed instead
of the original incoming HTTP verb.
  • Loading branch information...
1 parent 80b2689 commit 708a2abcb7508552fe048d773d2299d178be1236 @jperras jperras committed
Showing with 26 additions and 0 deletions.
  1. +19 −0 flask/testsuite/views.py
  2. +7 −0 flask/views.py
View
19 flask/testsuite/views.py
@@ -145,6 +145,25 @@ def head(self):
self.assert_equal(rv.data, '')
self.assert_equal(rv.headers['X-Method'], 'HEAD')
+ def test_method_override(self):
+ app = flask.Flask(__name__)
+
+ class Override(flask.views.MethodView):
+ def put(self):
+ return 'PUT'
+
+ def post(self):
+ return 'POST'
+
+ app.add_url_rule('/', view_func=Override.as_view('override'))
+ c = app.test_client()
+ rv = c.post('/')
+ self.assert_equal(rv.data, 'POST')
+ rv = c.put('/')
+ self.assert_equal(rv.data, 'PUT')
+ rv = c.post('/', headers=[('X-HTTP-Method-Override', 'PUT')])
+ self.assert_equal(rv.data, 'PUT')
+
def suite():
suite = unittest.TestSuite()
View
7 flask/views.py
@@ -142,6 +142,13 @@ def post(self):
def dispatch_request(self, *args, **kwargs):
meth = getattr(self, request.method.lower(), None)
+
+ # If the request method has been explicitly overriden, use that
+ # instead of the original HTTP verb.
+ if 'X-HTTP-Method-Override' in request.headers:
+ override = request.headers['X-HTTP-Method-Override']
+ meth = getattr(self, override.lower(), None)
+
# 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':

0 comments on commit 708a2ab

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