Skip to content

Instantly share code, notes, and snippets.

@bregenspan
Created March 22, 2012 18:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bregenspan/2161338 to your computer and use it in GitHub Desktop.
Save bregenspan/2161338 to your computer and use it in GitHub Desktop.
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
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment