Skip to content

Instantly share code, notes, and snippets.

@cgbystrom
Created June 27, 2012 12:06
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save cgbystrom/3003668 to your computer and use it in GitHub Desktop.
Save cgbystrom/3003668 to your computer and use it in GitHub Desktop.
WSGI middleware for serving CORS compatible requests
class CORSMiddleware(object):
"""Enable serving of CORS requests (http://en.wikipedia.org/wiki/Cross-origin_resource_sharing)"""
ALLOW_ORIGIN = "*"
ALLOW_HEADERS = "Origin, X-Requested-With, Content-Type"
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
if environ['REQUEST_METHOD'] == 'OPTIONS':
start_response('200 OK', [
('Access-Control-Allow-Origin', self.ALLOW_ORIGIN),
('Access-Control-Allow-Headers', self.ALLOW_HEADERS),
])
return ['POST']
else:
def cors_start_response(status, headers, exc_info=None):
headers.append(('Access-Control-Allow-Origin', self.ALLOW_ORIGIN))
headers.append(('Access-Control-Allow-Headers', self.ALLOW_HEADERS))
return start_response(status, headers, exc_info)
return self.app(environ, cors_start_response)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment