Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions src/nodenorm/handlers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,16 @@
import tornado.web

import nodenorm
from nodenorm.handlers.conflations import ValidConflationsHandler
from nodenorm.handlers.health import NodeNormHealthHandler
from nodenorm.handlers.normalized_nodes import NormalizedNodesHandler
from nodenorm.handlers.semantic_types import SemanticTypeHandler
from nodenorm.handlers.set_identifiers import SetIdentifierHandler
from nodenorm.handlers.version import VersionHandler


def build_handlers() -> dict[str, tuple[str, Callable]]:
"""Generate our handler mapping for the nodenorm API."""
from nodenorm.handlers.conflations import ValidConflationsHandler
from nodenorm.handlers.health import NodeNormHealthHandler
from nodenorm.handlers.normalized_nodes import NormalizedNodesHandler
from nodenorm.handlers.semantic_types import SemanticTypeHandler
from nodenorm.handlers.set_identifiers import SetIdentifierHandler
from nodenorm.handlers.version import VersionHandler

handler_collection = [
(r"/get_allowed_conflations?", ValidConflationsHandler),
Expand Down
28 changes: 28 additions & 0 deletions src/nodenorm/handlers/base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"""Shared handler behavior for NodeNormalization API endpoints."""

from biothings.web.handlers import BaseHandler


class NodeNormalizationBaseHandler(BaseHandler):
"""Base handler that keeps the lightweight BioThings handler plus CORS."""

cors_origin = "*"
cors_methods = "GET, POST, HEAD, OPTIONS"
cors_max_age = "600"

def set_default_headers(self):
super().set_default_headers()

origin = self.request.headers.get("Origin")
if origin is None:
return

requested_headers = self.request.headers.get("Access-Control-Request-Headers")

self.set_header("Access-Control-Allow-Origin", self.cors_origin)
self.set_header("Access-Control-Allow-Methods", self.cors_methods)
Comment on lines +22 to +23
self.set_header("Access-Control-Allow-Headers", requested_headers or "*")
self.set_header("Access-Control-Max-Age", self.cors_max_age)

def options(self, *args, **kwargs):
self.finish()
5 changes: 2 additions & 3 deletions src/nodenorm/handlers/conflations.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import logging

from biothings.web.handlers import BaseHandler

from nodenorm.handlers.base import NodeNormalizationBaseHandler

logger = logging.getLogger(__name__)


class ValidConflationsHandler(BaseHandler):
class ValidConflationsHandler(NodeNormalizationBaseHandler):
name = "allowed-conflations"

async def get(self):
Expand Down
5 changes: 2 additions & 3 deletions src/nodenorm/handlers/health.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@

from elasticsearch import AsyncElasticsearch

from biothings.web.handlers import BaseHandler

from nodenorm.biolink import BIOLINK_MODEL_VERSION
from nodenorm.handlers.base import NodeNormalizationBaseHandler


class NodeNormHealthHandler(BaseHandler):
class NodeNormHealthHandler(NodeNormalizationBaseHandler):
"""
Important Endpoints
* /_cat/nodes
Expand Down
4 changes: 2 additions & 2 deletions src/nodenorm/handlers/normalized_nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
import time
from typing import Union

from biothings.web.handlers import BaseHandler
from tornado.web import HTTPError

from nodenorm.biolink import toolkit
from nodenorm.handlers.base import NodeNormalizationBaseHandler
from nodenorm.namespace import NodeNormalizationAPINamespace

logger = logging.getLogger(__name__)
Expand All @@ -25,7 +25,7 @@ class NormalizedNode:
taxa: list[str]


class NormalizedNodesHandler(BaseHandler):
class NormalizedNodesHandler(NodeNormalizationBaseHandler):
"""
Mirror implementation to the renci implementation found at
https://nodenormalization-sri.renci.org/docs
Expand Down
4 changes: 2 additions & 2 deletions src/nodenorm/handlers/semantic_types.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
from biothings.web.handlers import BaseHandler
from tornado.web import HTTPError

from nodenorm.biolink import toolkit
from nodenorm.handlers.base import NodeNormalizationBaseHandler


class SemanticTypeHandler(BaseHandler):
class SemanticTypeHandler(NodeNormalizationBaseHandler):
"""
Mirror implementation to the renci implementation found at
https://nodenormalization-sri.renci.org/docs
Expand Down
5 changes: 2 additions & 3 deletions src/nodenorm/handlers/set_identifiers.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,9 @@
import uuid
from typing import Optional

from biothings.web.handlers import BaseHandler

from tornado.web import HTTPError

from nodenorm.handlers.base import NodeNormalizationBaseHandler
from nodenorm.handlers.normalized_nodes import get_normalized_nodes
from nodenorm.namespace import NodeNormalizationAPINamespace

Expand All @@ -24,7 +23,7 @@ class SetIDResponse:
setid: Optional[str] = None


class SetIdentifierHandler(BaseHandler):
class SetIdentifierHandler(NodeNormalizationBaseHandler):
"""
Mirror implementation to the renci implementation found at
https://nodenormalization-sri.renci.org/docs
Expand Down
5 changes: 2 additions & 3 deletions src/nodenorm/handlers/version.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
from biothings.web.handlers import BaseHandler

from nodenorm.handlers.base import NodeNormalizationBaseHandler
from nodenorm.version import get_version


class VersionHandler(BaseHandler):
class VersionHandler(NodeNormalizationBaseHandler):
name = "version"

async def get(self, *args, **kwargs):
Expand Down
15 changes: 9 additions & 6 deletions src/nodenorm/namespace.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,9 @@ def load_configuration(self, option_configuration: tornado.options.OptionParser)

configuration.update(default_configuration)

if option_configuration.conf is not None:
optional_configuration = pathlib.Path(option_configuration.conf).absolute().resolve()
optional_configuration_file = getattr(option_configuration, "conf", None)
if optional_configuration_file is not None:
optional_configuration = pathlib.Path(optional_configuration_file).absolute().resolve()
if optional_configuration.exists():
with open(optional_configuration, "r", encoding="utf-8") as handle:
configuration.update(json.load(handle))
Expand All @@ -155,11 +156,13 @@ def load_configuration(self, option_configuration: tornado.options.OptionParser)
configuration_namespace = types.SimpleNamespace(**configuration)

# override options
if option_configuration.host is not None:
configuration_namespace.webserver["HOST"] = option_configuration.host
option_host = getattr(option_configuration, "host", None)
if option_host is not None:
configuration_namespace.webserver["HOST"] = option_host

if option_configuration.port is not None:
configuration_namespace.webserver["PORT"] = option_configuration.port
option_port = getattr(option_configuration, "port", None)
if option_port is not None:
configuration_namespace.webserver["PORT"] = option_port

return configuration_namespace

Expand Down
50 changes: 50 additions & 0 deletions tests/test_cors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import tornado.web
from tornado.testing import AsyncHTTPTestCase

from nodenorm.handlers.base import NodeNormalizationBaseHandler

ORIGIN = "https://translatorsri.github.io"


class PreflightHandler(NodeNormalizationBaseHandler):
async def get(self):
self.finish({"ok": True})


def assert_cors_headers(headers, allowed_headers="*"):
assert headers["Access-Control-Allow-Origin"] == "*"
assert "Access-Control-Allow-Credentials" not in headers
assert headers["Access-Control-Allow-Methods"] == "GET, POST, HEAD, OPTIONS"
assert headers["Access-Control-Allow-Headers"] == allowed_headers
assert headers["Access-Control-Max-Age"] == "600"


class TestCorsHeaders(AsyncHTTPTestCase):
def get_app(self) -> tornado.web.Application:
return tornado.web.Application(
[
(r"/version", PreflightHandler),
(r"/get_normalized_nodes", PreflightHandler),
]
)

def test_get_response_includes_cors_headers_for_browser_origin(self):
response = self.fetch("/version", headers={"Origin": ORIGIN})

assert response.code == 200
assert_cors_headers(response.headers)

def test_preflight_returns_cors_headers(self):
response = self.fetch(
"/get_normalized_nodes",
method="OPTIONS",
headers={
"Origin": ORIGIN,
"Access-Control-Request-Method": "POST",
"Access-Control-Request-Headers": "content-type",
},
)

assert response.code == 200
assert response.body == b""
assert_cors_headers(response.headers, "content-type")