Skip to content

Commit

Permalink
add allow_cors option (#73)
Browse files Browse the repository at this point in the history
  • Loading branch information
MarkParker5 authored Sep 23, 2023
1 parent 3c9fddb commit e7e8e11
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
14 changes: 14 additions & 0 deletions tornado_swagger/_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,27 @@ def data_received(self, chunk: bytes):

class SwaggerUiHandler(TornadoBaseHandler):
SWAGGER_HOME_TEMPLATE = ""
allow_cors: bool = False

def get(self):
self.write(self.SWAGGER_HOME_TEMPLATE)

def options(self):
if self.allow_cors:
self.set_header("Access-Control-Allow-Origin", "*")
self.set_header("Access-Control-Allow-Headers", "Content-Type")
self.set_header("Access-Control-Allow-Methods", "GET, OPTIONS")


class SwaggerSpecHandler(TornadoBaseHandler):
SWAGGER_SPEC = ""
allow_cors: bool = False

def get(self):
self.write(self.SWAGGER_SPEC)

def options(self):
if self.allow_cors:
self.set_header("Access-Control-Allow-Origin", "*")
self.set_header("Access-Control-Allow-Headers", "Content-Type")
self.set_header("Access-Control-Allow-Methods", "GET, OPTIONS")
5 changes: 4 additions & 1 deletion tornado_swagger/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ def setup_swagger(
security_definitions: dict = None,
security: list = None,
display_models: bool = True,
api_definition_version: str = API_SWAGGER_2
api_definition_version: str = API_SWAGGER_2,
allow_cors: bool = False,
):
"""Inject swagger ui to application routes"""
swagger_schema = generate_doc_from_endpoints(
Expand All @@ -79,6 +80,8 @@ def setup_swagger(
]

SwaggerSpecHandler.SWAGGER_SPEC = swagger_schema
SwaggerSpecHandler.allow_cors = allow_cors
SwaggerUiHandler.allow_cors = allow_cors

with open(os.path.join(STATIC_PATH, "ui.html"), "r", encoding="utf-8") as f:
SwaggerUiHandler.SWAGGER_HOME_TEMPLATE = (
Expand Down

0 comments on commit e7e8e11

Please sign in to comment.