Forked from valsteen/django-crossdomainxhr-middleware.py
Last active
August 29, 2015 13:57
-
-
Save decklord/9400750 to your computer and use it in GitHub Desktop.
Enables to do cross domain requests with django
This file contains hidden or 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 | |
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