Skip to content

Instantly share code, notes, and snippets.

@lbenitez000
Last active December 20, 2016 00:51
Show Gist options
  • Save lbenitez000/dc34e8a7815cc3599583 to your computer and use it in GitHub Desktop.
Save lbenitez000/dc34e8a7815cc3599583 to your computer and use it in GitHub Desktop.
A CORS middleware for the Falcon Framework <http://falconframework.org/>
""" A CORS middleware for the Falcon Framework <http://falconframework.org/>
"""
__author__ = "Luis Benitez"
__license__ = "MIT"
from falcon import HTTP_METHODS
class CorsMiddleware(object):
"""Implements (partially) the Cross Origin Resource Sharing specification
Link: http://www.w3.org/TR/cors/
"""
ALLOWED_ORIGINS = ['*']
def process_resource(self, req, resp, resource):
origin = req.get_header('Origin')
if origin:
# If there is no Origin header, then it is not a valid CORS request
acrm = req.get_header('Access-Control-Request-Method')
acrh = req.get_header('Access-Control-Request-Headers')
if req.method == 'OPTIONS' and acrm and acrh:
# Method is OPTIONS & ACRM & ACRH Headers => This is a preflight request
# TODO Validate ACRM & ACRH
# Set ACAH to echo ACRH
resp.set_header('Access-Control-Allow-Headers', acrh)
# Optionally set ACMA
# resp.set_header('Access-Control-Max-Age', '60')
# Find implemented methods
allowed_methods = []
for method in HTTP_METHODS:
allowed_method = getattr(resource, 'on_' + method.lower(), None)
if allowed_method:
allowed_methods.append(method)
# Fill ACAM
resp.set_header('Access-Control-Allow-Methods', ','.join(sorted(allowed_methods)))
def process_response(self, req, resp, resource):
origin = req.get_header('Origin')
if origin:
# If there is no Origin header, then it is not a valid CORS request
if '*' in self.ALLOWED_ORIGINS:
resp.set_header('Access-Control-Allow-Origin', '*')
elif origin in self.ALLOWED_ORIGINS:
resp.set_header('Access-Control-Allow-Origin', origin)
@lwcolton
Copy link

There is a package for this now: https://github.com/lwcolton/falcon-cors

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