Skip to content
Myr

methodoverrides.rst

This file

Path

docs/patterns/methodoverrides.rst

42 lines · 1.4 KiB

Last changed by

Merge branch '1.0.x'David Lordbefore adoption2236ba9

History of this file

Take it

The walk stopped after 200 commits: lines older than 62406e6 point at it.

Merge pull request #2352 from davidism/json-object-hookDavid Lordbefore adoption62406e6

lines 1–4why, one step back
1Adding HTTP Method Overrides
2============================34Some HTTP proxies do not support arbitrary HTTP methods or newer HTTP

Merge branch '1.0.x'David Lordbefore adoption2236ba9

line 5why, one step back
5methods (such as PATCH). In that case it's possible to "proxy" HTTP

Merge pull request #2352 from davidism/json-object-hookDavid Lordbefore adoption62406e6

lines 6–8why, one step back
6methods through another HTTP method in total violation of the protocol.
78The way this works is by letting the client do an HTTP POST request and

Merge branch '1.0.x'David Lordbefore adoption2236ba9

lines 9–10why, one step back
9set the ``X-HTTP-Method-Override`` header. Then the method is replaced
10with the header value before being passed to Flask.

Merge pull request #2352 from davidism/json-object-hookDavid Lordbefore adoption62406e6

line 11why, one step back
11

Merge branch '1.0.x'David Lordbefore adoption2236ba9

line 12why, one step back
12This can be accomplished with an HTTP middleware::

Merge pull request #2352 from davidism/json-object-hookDavid Lordbefore adoption62406e6

lines 13–36why, one step back
13
14 class HTTPMethodOverrideMiddleware(object):15 allowed_methods = frozenset([16 'GET',17 'HEAD',18 'POST',19 'DELETE',20 'PUT',21 'PATCH',22 'OPTIONS'23 ])24 bodyless_methods = frozenset(['GET', 'HEAD', 'OPTIONS', 'DELETE'])2526 def __init__(self, app):27 self.app = app2829 def __call__(self, environ, start_response):30 method = environ.get('HTTP_X_HTTP_METHOD_OVERRIDE', '').upper()31 if method in self.allowed_methods:32 environ['REQUEST_METHOD'] = method33 if method in self.bodyless_methods:34 environ['CONTENT_LENGTH'] = '0'35 return self.app(environ, start_response)36

Merge branch '1.0.x'David Lordbefore adoption2236ba9

line 37why, one step back
37To use this with Flask, wrap the app object with the middleware::

Merge pull request #2352 from davidism/json-object-hookDavid Lordbefore adoption62406e6

lines 38–42why, one step back
38
39 from flask import Flask4041 app = Flask(__name__)42 app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)