restless
restless copied to clipboard
Adding CORS headers to a particular resource
How would I go about enabling CORS on a per resource basis. Thanks in advance for any pointers.
There is hacky workaround this:
class PostResource(restless.tnd.TornadoResource):
def is_authenticated(self):
return True
def create(self, *args, **kwargs):
self.r_handler.add_header('Access-Control-Allow-Origin', '*')
Since I can not be able to add CORS header in __init__, __call__, __new__
.
I put header in each end point.
I will be working on converting this workarounD to decorator
like
@cors(origin='*')
def create(self, *args, **kwargs):
...
#!/usr/bin/env python
# coding:utf-8
# noinspection SpellCheckingInspection
def cors(origins=['http://127.0.0.1:9001', 'http://localhost:9001', 'http://stackoverflow.com']):
"""
Usage
class RestlessResource(restless.tnd.TornadoResource):
@api.extensions.cors(origins=['http://stackoverflow.com'])
def list(self, *args, **kwargs):
...
:param origins:
:return:
"""
def real_decorator(func):
# Passing parameters to decorators
# http://stackoverflow.com/a/5929165/1766716
def wrapper(*args, **kwargs):
self = args[0]
if self.r_handler.request.headers.get('origin') in origins:
# Thanks to http://stackoverflow.com/a/7454204/1766716
self.r_handler.add_header('Access-Control-Allow-Origin', self.r_handler.request.headers['origin'])
return func(*args, **kwargs)
return wrapper
return real_decorator
Usage
class RestlessResource(restless.tnd.TornadoResource):
@api.extensions.cors(origins=['http://stackoverflow.com'])
def list(self, *args, **kwargs):
...