Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save axelpale/3263576 to your computer and use it in GitHub Desktop.
Save axelpale/3263576 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).
# -*- coding: utf-8 -*-
# Source:
# https://gist.github.com/3263576
import re
from django.utils.text import compress_string
from django.utils.cache import patch_vary_headers
from django import http
import settings
# How to default:
# http://www.codekoala.com/blog/2009/custom-django-settings-and-default-values/
CROSS_DOMAIN_XHR_ALLOWED_ORIGINS = getattr(
settings, 'CROSS_DOMAIN_XHR_ALLOWED_ORIGINS', '*')
CROSS_DOMAIN_XHR_ALLOWED_METHODS = getattr(
settings, 'CROSS_DOMAIN_XHR_ALLOWED_METHODS',
['POST', 'GET', 'OPTIONS', 'PUT', 'DELETE'])
class CrossDomainXhrMiddleware(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'] = CROSS_DOMAIN_XHR_ALLOWED_ORIGINS
response['Access-Control-Allow-Methods'] = ",".join(CROSS_DOMAIN_XHR_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'] = CROSS_DOMAIN_XHR_ALLOWED_ORIGINS
response['Access-Control-Allow-Methods'] = ",".join(CROSS_DOMAIN_XHR_ALLOWED_METHODS)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment