public

Middlware to allow's your django server to respond appropriately to cross domain XHR (postMessage html5 API).

  • Download Gist
django-crossdomainxhr-middleware.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
import re
 
from django.utils.text import compress_string
from django.utils.cache import patch_vary_headers
 
from django import http
 
try:
import settings
XS_SHARING_ALLOWED_ORIGINS = settings.XS_SHARING_ALLOWED_ORIGINS
XS_SHARING_ALLOWED_METHODS = settings.XS_SHARING_ALLOWED_METHODS
except:
XS_SHARING_ALLOWED_ORIGINS = '*'
XS_SHARING_ALLOWED_METHODS = ['POST','GET','OPTIONS', 'PUT', 'DELETE']
 
 
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
"""
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 )
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

Thanks. This helped a lot.

This is great, thanks!

awesome, thanks a lot!

Very nice, thank you! If I must say something constructive, I would name the class to XsSharingMiddleware. Middleware-postfix seems to be the convention amongst Django middlewares. For example: 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware'. And what does Xs mean? Anyway, thanks for the gist, I will put it to good use :)

Thanks @doph. I will rewrite, but anyway, i'm not working with django anymore for a long time, so if you want to fork and maintain this snippet updated with django, i will appreciate a lot!

The "xs" suffix was just a "gotcha" with XSS. I could name it XssSharing , but i prefer to let the last 's' mixed with sharing. You can rename as you like.

@doph @frangossauro i've been using this awesome gist and customized it a bit to support allowed headers, which i needed to make CORS work for my project. you can see my fork here: https://gist.github.com/2941258

made my day. thanks alot

Thanks for this! :)

Thanks, that's really helpful.

Quick question: What changes should I make in order to allow certain urls of my site to be "open" for cors?

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.