Created
November 6, 2017 07:40
-
-
Save recall704/da9892a35efea65b9c8610ae47694b95 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import inspect | |
from tornado.web import RequestHandler | |
from tornado.web import asynchronous as wrapper | |
def _get_class_that_defined_method(meth): | |
for cls in inspect.getmro(meth.__self__.__class__): | |
if meth.__name__ in cls.__dict__: return cls # noqa | |
return None | |
class CorsMixin(object): | |
# CORS_ORIGIN = None | |
CORS_ORIGIN = '*' | |
CORS_HEADERS = 'Content-Type' | |
CORS_METHODS = "GET,PUT,POST,DELETE,OPTIONS,PATCH" | |
CORS_MAX_AGE = 86400 | |
CORS_CREDENTIALS = True | |
CORS_EXPOSE_HEADERS = 'Location, X-WP-TotalPages' | |
def set_default_headers(self): | |
if self.CORS_ORIGIN: | |
self.set_header("Access-Control-Allow-Origin", self.CORS_ORIGIN) | |
if self.CORS_HEADERS: | |
self.set_header('Access-Control-Allow-Headers', self.CORS_HEADERS) | |
if self.CORS_METHODS: | |
self.set_header('Access-Control-Allow-Methods', self._get_methods()) # noqa | |
if self.CORS_MAX_AGE: | |
self.set_header('Access-Control-Max-Age', self.CORS_MAX_AGE) | |
if self.CORS_CREDENTIALS: | |
self.set_header('Access-Control-Allow-Credentials', | |
"true" if self.CORS_CREDENTIALS else "false") | |
if self.CORS_EXPOSE_HEADERS: | |
self.set_header('Access-Control-Expose-Headers', self.CORS_EXPOSE_HEADERS) # noqa | |
@wrapper | |
def options(self, *args, **kwargs): | |
if self.CORS_HEADERS: | |
self.set_header('Access-Control-Allow-Headers', self.CORS_HEADERS) | |
if self.CORS_METHODS: | |
self.set_header('Access-Control-Allow-Methods', self.CORS_METHODS) | |
else: | |
self.set_header('Access-Control-Allow-Methods', self._get_methods()) # noqa | |
if self.CORS_CREDENTIALS is not None: | |
self.set_header('Access-Control-Allow-Credentials', | |
"true" if self.CORS_CREDENTIALS else "false") # noqa | |
if self.CORS_MAX_AGE: | |
self.set_header('Access-Control-Max-Age', self.CORS_MAX_AGE) | |
if self.CORS_EXPOSE_HEADERS: | |
self.set_header('Access-Control-Expose-Headers', self.CORS_EXPOSE_HEADERS) # noqa | |
self.set_status(204) | |
self.finish() | |
def _get_methods(self): | |
supported_methods = [method.lower() for method in self.SUPPORTED_METHODS] # noqa | |
# ['get', 'put', 'post', 'patch', 'delete', 'options'] | |
methods = [] | |
for meth in supported_methods: | |
instance_meth = getattr(self, meth) | |
if not meth: | |
continue | |
handler_class = _get_class_that_defined_method(instance_meth) | |
if not handler_class is RequestHandler: # noqa | |
methods.append(meth.upper()) | |
return ", ".join(methods) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment