Skip to content

Instantly share code, notes, and snippets.

@lxyu
Last active December 22, 2015 21:29
Show Gist options
  • Save lxyu/6534068 to your computer and use it in GitHub Desktop.
Save lxyu/6534068 to your computer and use it in GitHub Desktop.
Flask CROS(Cross-Origin Resource Sharing) decorator simplified
import datetime
import functools
from flask import (
current_app,
make_response,
request
)
def cros(origin, methods=None, max_age=3600):
methods = methods or ['OPTIONS', 'GET', 'POST', 'PUT', 'DELETE']
methods = ', '.join(m.upper() for m in methods)
if isinstance(max_age, datetime.timedelta):
max_age = max_age.total_seconds()
def decorator(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
if request.method == 'OPTIONS':
resp = current_app.make_default_options_response()
resp.headers.pop("allow")
else:
resp = make_response(func(*args, **kwargs))
resp.headers.extend({
"Access-Control-Allow-Methods": methods,
"Access-Control-Allow-Origin": origin,
"Access-Control-Max-Age": max_age,
"Access-Control-Allow-Headers": "Content-Type",
})
return resp
return wrapped
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment