Forked from vicalejuri/django-crossdomainxhr-middleware.py
Created
December 10, 2013 11:32
-
-
Save bentappin/7889266 to your computer and use it in GitHub Desktop.
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
# encoding: utf-8 | |
from django import http | |
from django.conf import settings | |
try: | |
XS_SHARING_ALLOWED_ORIGINS = settings.XS_SHARING_ALLOWED_ORIGINS | |
except AttributeError: | |
XS_SHARING_ALLOWED_ORIGINS = '*' | |
try: | |
XS_SHARING_ALLOWED_METHODS = settings.XS_SHARING_ALLOWED_METHODS | |
except AttributeError: | |
XS_SHARING_ALLOWED_METHODS = ['POST','GET','OPTIONS', 'PATCH', 'PUT', | |
'DELETE'] | |
class XsSharing(object): | |
""" | |
This middleware allows cross-domain XHR using the html5 postMessage API. | |
Access-Control-Allow-Origin: http://foo.example.com | |
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, PATCH, DELETE | |
""" | |
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([ | |
'Content-Type', 'Depth', 'User-Agent', 'X-File-Size', | |
'X-Requested-With', 'If-Modified-Since', 'X-File-Name', | |
'Cache-Control']) | |
return response | |
return None | |
def process_response(self, request, response): | |
# Avoid unnecessary work | |
if response.has_header('Access-Control-Allow-Origin'): | |
return response | |
response['Access-Control-Allow-Origin'] = XS_SHARING_ALLOWED_ORIGINS | |
response['Access-Control-Allow-Methods'] = ",".join(XS_SHARING_ALLOWED_METHODS) | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment