Skip to content

Instantly share code, notes, and snippets.

@jake-nz
Last active August 29, 2015 13:58
Show Gist options
  • Save jake-nz/10337880 to your computer and use it in GitHub Desktop.
Save jake-nz/10337880 to your computer and use it in GitHub Desktop.
Tastypie resource base class that allows for cross domain requests by adding CORS headers. - Handles all responses from the resource even ImmediateHttpResponse exceptions.
from tastypie.resources import Resource
from tastypie.exceptions import ImmediateHttpResponse
from django.http import HttpResponse
class CorsResource(Resource):
""" adds CORS headers for cross-domain requests """
def patch_response(self, response):
allowed_headers = ['Content-Type', 'Authorization']
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Headers'] = ','.join(allowed_headers)
return response
def wrap_view(self, view):
""" calls view and patches resonse headers
or
catches ImmediateHttpResponse, patches headers and re-raises
"""
# first do what the original wrap_view wanted to do
wrapper = super(CorsResource, self).wrap_view(view)
# now wrap that to patch the headers
def wrapper2(*args, **kwargs):
try:
response = wrapper(*args, **kwargs)
return self.patch_response(response)
except ImmediateHttpResponse, exception:
response = self.patch_response(exception.response)
print 'caught and patched'
# re-raise - we could return a response but then anthing wrapping
# this and expecting an exception would be confused
raise ImmediateHttpResponse(response)
return wrapper2
def method_check(self, request, allowed=None):
""" Handle OPTIONS requests """
if request.method.upper() == 'OPTIONS':
if allowed is None:
allowed = []
allows = ','.join(allowed).upper()
response = HttpResponse(allows)
response['Allow'] = allows
raise ImmediateHttpResponse(response=response)
return super(CorsResource, self).method_check(request, allowed)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment