Skip to content

Instantly share code, notes, and snippets.

@an01f01
Last active February 25, 2022 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save an01f01/87293e4f2059da1500c2ec1a50982fd3 to your computer and use it in GitHub Desktop.
Save an01f01/87293e4f2059da1500c2ec1a50982fd3 to your computer and use it in GitHub Desktop.
This is a Tornado base handler that implements CORS support to a REST API
class BaseHandler(tornado.web.RequestHandler):
"""
Base handler setting up the default headers for CORS
"""
def set_default_headers(self):
self.set_header("Access-Control-Allow-Origin", "*")
self.set_header("Access-Control-Allow-Headers", "x-requested-with")
self.set_header('Access-Control-Allow-Methods', 'POST, GET, DELETE, PUT')
"""
Base handler preparing requests and redirect to HTTPS
"""
def prepare(self):
if self.request.protocol == 'http':
self.redirect('https://' + self.request.host, permanent=False)
"""
Base handler to be used instead of RequestHandler
"""
def write_error(self, status_code, **kwargs):
if status_code in [403, 404, 500, 503]:
self.write('Error %s' % status_code)
else:
self.write('BOOM!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment