Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save decklord/9400750 to your computer and use it in GitHub Desktop.
Save decklord/9400750 to your computer and use it in GitHub Desktop.
Enables to do cross domain requests with django
from django import http
from django.conf import settings
class XsSharingMiddleware(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
"""
def set_response(self, response):
allowed_origin = settings.XS_SHARING_ALLOWED_ORIGIN
allowed_methods = ",".join(settings.XS_SHARING_ALLOWED_METHODS)
allowed_headers = ",".join(settings.XS_SHARING_ALLOWED_HEADERS)
response['Access-Control-Allow-Origin'] = allowed_origin
response['Access-Control-Allow-Methods'] = allowed_methods
response['Access-Control-Allow-Headers'] = allowed_headers
return response
def process_request(self, request):
if 'HTTP_ACCESS_CONTROL_REQUEST_METHOD' in request.META:
response = http.HttpResponse()
response = self.set_response(response)
return response
return None
def process_response(self, request, response):
# Avoid unnecessary work
if response.has_header('Access-Control-Allow-Origin'):
return response
response = self.set_response(response)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment