Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Quick way to set CORS headers on django-tastypie resources
class CORSResource(object):
"""
Adds CORS headers to resources that subclass this.
"""
def create_response(self, *args, **kwargs):
response = super(CORSResource, self).create_response(*args, **kwargs)
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Headers'] = 'Content-Type'
return response
def method_check(self, request, allowed=None):
if allowed is None:
allowed = []
request_method = request.method.lower()
allows = ','.join(map(str.upper, allowed))
if request_method == 'options':
response = HttpResponse(allows)
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Headers'] = 'Content-Type'
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
@PuercoPop

This comment has been minimized.

Copy link

PuercoPop commented Oct 25, 2013

Thanks! Only the import statements are missing

from string import upper
from django.http import HttpResponse
from tastypie.exceptions import ImmediateHttpResponse

Using string's upper instead of taking it from str for it to play nice with unicode

@trawick

This comment has been minimized.

Copy link

trawick commented Feb 17, 2014

It also needs to import http from tastypie, for HttpMethodNotAllowed.

@marcelometal

This comment has been minimized.

Copy link

marcelometal commented Jan 9, 2016

django-cors-headers is a good alternative

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.