Skip to content

Instantly share code, notes, and snippets.

@diarmuidbourke
Last active December 15, 2015 12:58
Show Gist options
  • Save diarmuidbourke/5263452 to your computer and use it in GitHub Desktop.
Save diarmuidbourke/5263452 to your computer and use it in GitHub Desktop.
cors preflight response
def cors_tween_factory(handler, registry):
def handle_cors(request):
if request.method == "OPTIONS":
allowed_hosts = ['http://127.0.0.1:8000']
cors_headers = [
('Access-Control-Allow-Credentials', "true"),
('Access-Control-Allow-Origin', request.headers['origin']),
('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'),
('Access-Control-Allow-Headers',
"""X-CSRF-Token, X-Requested-With, Accept, """ +
"""Accept-Version, Content-Length, Content-MD5, """ +
"""Content-Type, Date, X-Api-Version"""),
('Access-Control-Max-Age', '60')]
if request.headers['origin'] in allowed_hosts:
for header in cors_headers:
request.response.headers[header[0]] = header[1]
# Respond to options request
return request.response
else:
# Respond to other requests
return handler(request)
# Return the tween to be called
return handle_cors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment