Adding HTTP Method Overrides

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

The way this works is by letting the client do an HTTP POST request and set the X-HTTP-Method-Override header. Then the method is replaced with 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. def __init__(self, app):
  13. self.app = app
  14. def __call__(self, environ, start_response):
  15. method = environ.get('HTTP_X_HTTP_METHOD_OVERRIDE', '').upper()
  16. if method in self.allowed_methods:
  17. environ['REQUEST_METHOD'] = method
  18. if method in self.bodyless_methods:
  19. environ['CONTENT_LENGTH'] = '0'
  20. return self.app(environ, start_response)

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

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