Adding HTTP Method Overrides

Some HTTP proxies do not support arbitrary HTTP methods or newer HTTPmethods (such as PATCH). In that case it’s possible to “proxy” HTTPmethods through another HTTP method in total violation of the protocol.

The way this works is by letting the client do an HTTP POST request andset the X-HTTP-Method-Override header. Then the method is replacedwith the header value before being passed to Flask.

This can be accomplished with an HTTP middleware:

  1. class HTTPMethodOverrideMiddleware(object):
  2. allowed_methods = frozenset([
  3. 'GET',
  4. 'HEAD',
  5. 'POST',
  6. 'DELETE',
  7. 'PUT',
  8. 'PATCH',
  9. 'OPTIONS'
  10. ])
  11. bodyless_methods = frozenset(['GET', 'HEAD', 'OPTIONS', 'DELETE'])
  12.  
  13. def __init__(self, app):
  14. self.app = app
  15.  
  16. def __call__(self, environ, start_response):
  17. method = environ.get('HTTP_X_HTTP_METHOD_OVERRIDE', '').upper()
  18. if method in self.allowed_methods:
  19. environ['REQUEST_METHOD'] = method
  20. if method in self.bodyless_methods:
  21. environ['CONTENT_LENGTH'] = '0'
  22. return self.app(environ, start_response)

To use this with Flask, wrap the app object with the middleware:

  1. from flask import Flask
  2.  
  3. app = Flask(__name__)
  4. app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)