This repository has been archived by the owner on Oct 17, 2019. It is now read-only.
/
__init__.py
51 lines (39 loc) · 1.5 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# -*- coding: utf-8 -*-
import inspect
import logging
from tornado.web import asynchronous, RequestHandler
from tornado_cors import custom_decorator
def _get_class_that_defined_method(meth):
for cls in inspect.getmro(meth.__self__.__class__):
if meth.__name__ in cls.__dict__: return cls
return None
class CorsMixin(object):
CORS_ORIGIN = None
CORS_HEADERS = None
CORS_METHODS = None
CORS_MAX_AGE = 86400
def prepare(self):
if self.CORS_ORIGIN:
self.set_header('Access-Control-Allow-Origin', self.CORS_ORIGIN)
@custom_decorator.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())
if self.CORS_MAX_AGE:
self.set_header('Access-Control-Max-Age', self.CORS_MAX_AGE)
self.set_status(204)
self.finish()
def _get_methods(self):
methods = []
for meth in ['get', 'put', 'post', 'patch', 'delete', 'options']:
instance_meth = getattr(self, meth)
if not meth:
continue
handler_class = _get_class_that_defined_method(instance_meth)
if not handler_class is RequestHandler:
methods.append(meth.upper())
return ", ".join(methods)