Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jessykate/2941258 to your computer and use it in GitHub Desktop.
Save jessykate/2941258 to your computer and use it in GitHub Desktop.
Middlware to allow's your django server to respond appropriately to cross domain XHR (postMessage html5 API).
import re
from django.utils.text import compress_string
from django.utils.cache import patch_vary_headers
from django import http
'''
EXAMPLE USAGE:
Put this file in a directory called, eg, 'middleware,' inside your django
project. Make sure to create an __init__.py file in the directory so it can
be included as a module.
Set the values for
settings.XS_SHARING_ALLOWED_ORIGINS
settings.XS_SHARING_ALLOWED_METHODS
settings.XS_SHARING_ALLOWED_HEADERS
in settings.py. Then include
'modernomad.middleware.crossdomainxhr.CORSMiddleware'
in MIDDLEWARE_CLASSES in settings.py.
'''
try:
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
except:
XS_SHARING_ALLOWED_ORIGINS = ''
XS_SHARING_ALLOWED_METHODS = ['POST','GET','OPTIONS', 'PUT', 'DELETE']
XS_SHARING_ALLOWED_HEADERS = []
class XsSharing(object):
"""
This middleware allows cross-domain XHR using the html5 postMessage API.
eg.
Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE
Access-Control-Allow-Methods: ["Content-Type"]
"""
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 )
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
@prasanthn
Copy link

The code doesn't seem to read values from settings.py . The try block always throws exception --- we need django.conf.settings and it will fail unless we specify all three values.

I have a fork that fixes this. But I have renamed both the file and the class.

https://gist.github.com/prasanthn/5450772 .

@brendonjohn
Copy link

thanks @jessykate, I have also found this useful 😄

@uiandwe
Copy link

uiandwe commented Aug 16, 2019

thank you!! This works perfectly well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment