public
Last active

Mixin to supply Tastypie resource with support for X-HTTP-Method-Override headers, using jacobian's patch from https://github.com/toastdriven/django-tastypie/pull/351

  • Download Gist
gistfile1.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
class XHMOMixin(object):
"""
Use to supply a Tastypie resource with support for X-HTTP-Method-Override
headers, e.g.:
`class HomeResource(XHMOMixin, ModelResource):`
"""
 
def method_check(self, request, allowed=None):
"""
Ensures that the HTTP method used on the request is allowed to be
handled by the resource.
 
Patched with X-HTTP-Method-Override:
https://github.com/toastdriven/django-tastypie/pull/351
 
Takes an ``allowed`` parameter, which should be a list of lowercase
HTTP methods to check against. Usually, this looks like::
 
# The most generic lookup.
self.method_check(request, self._meta.allowed_methods)
 
# A lookup against what's allowed for list-type methods.
self.method_check(request, self._meta.list_allowed_methods)
 
# A useful check when creating a new endpoint that only handles
# GET.
self.method_check(request, ['get'])
"""
if allowed is None:
allowed = []
 
# Normally we'll just use request.method to determine the request
# method. However, since some bad clients can't support all HTTP
# methods, we allow overloading POST requests with a
# X-HTTP-Method-Override header. This allows POST requests to
# masquerade as different methods.
request_method = request.method.lower()
if request_method == 'post' and 'HTTP_X_HTTP_METHOD_OVERRIDE' in request.META:
request_method = request.META['HTTP_X_HTTP_METHOD_OVERRIDE'].lower()
 
allows = ','.join(map(str.upper, allowed))
 
if request_method == "options":
response = HttpResponse(allows)
response['Allow'] = allows
raise ImmediateHttpResponse(response=response)
 
if not request_method in allowed:
response = http.HttpMethodNotAllowed(allows)
response['Allow'] = allows
raise ImmediateHttpResponse(response=response)
 
return request_method

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.