Created
November 16, 2011 08:56
-
-
Save strogonoff/1369619 to your computer and use it in GitHub Desktop.
Django middleware for cross-domain XHR.
WARNING: Defaults are unsafe here. Make sure to set proper restrictions in production!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django import http | |
try: | |
from django.conf import settings | |
XS_SHARING_ALLOWED_ORIGINS = settings.XS_SHARING_ALLOWED_ORIGINS | |
XS_SHARING_ALLOWED_METHODS = settings.XS_SHARING_ALLOWED_METHODS | |
XS_SHARING_ALLOWED_HEADERS = settings.XS_SHARING_ALLOWED_HEADERS | |
XS_SHARING_ALLOWED_CREDENTIALS = settings.XS_SHARING_ALLOWED_CREDENTIALS | |
except AttributeError: | |
XS_SHARING_ALLOWED_ORIGINS = '*' | |
XS_SHARING_ALLOWED_METHODS = ['POST', 'GET', 'OPTIONS', 'PUT', 'DELETE'] | |
XS_SHARING_ALLOWED_HEADERS = ['Content-Type', '*'] | |
XS_SHARING_ALLOWED_CREDENTIALS = 'true' | |
class XsSharing(object): | |
""" | |
This middleware allows cross-domain XHR using the html5 postMessage API. | |
Access-Control-Allow-Origin: http://foo.example | |
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE | |
Based off https://gist.github.com/426829 | |
""" | |
def process_request(self, request): | |
if 'HTTP_ACCESS_CONTROL_REQUEST_METHOD' in request.META: | |
response = http.HttpResponse() | |
response['Access-Control-Allow-Origin'] = XS_SHARING_ALLOWED_ORIGINS | |
response['Access-Control-Allow-Methods'] = ",".join( XS_SHARING_ALLOWED_METHODS ) | |
response['Access-Control-Allow-Headers'] = ",".join( XS_SHARING_ALLOWED_HEADERS ) | |
response['Access-Control-Allow-Credentials'] = XS_SHARING_ALLOWED_CREDENTIALS | |
return response | |
return None | |
def process_response(self, request, response): | |
response['Access-Control-Allow-Origin'] = XS_SHARING_ALLOWED_ORIGINS | |
response['Access-Control-Allow-Methods'] = ",".join( XS_SHARING_ALLOWED_METHODS ) | |
response['Access-Control-Allow-Headers'] = ",".join( XS_SHARING_ALLOWED_HEADERS ) | |
response['Access-Control-Allow-Credentials'] = XS_SHARING_ALLOWED_CREDENTIALS | |
return response |
There is any special reason you assign variables outside class instead of init of the class ?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I had to add the extra auth headers and then this worked great! Couldn't get the other GIST about CORSResource for Tastypie to work. This is how I configured it: