Skip to content

Commit

Permalink
Re-enable CORS
Browse files Browse the repository at this point in the history
  • Loading branch information
juhoinkinen committed Apr 4, 2024
1 parent a94f707 commit beac55c
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 8 deletions.
8 changes: 7 additions & 1 deletion annif/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ def create_flask_app(config_name: str | None = None) -> Flask:
def create_cx_app(config_name: str | None = None) -> FlaskApp:
"""Create a Connexion app to be used for the API."""
import connexion
from connexion.middleware import MiddlewarePosition
from starlette.middleware.cors import CORSMiddleware

# from flask_cors import CORS # TODO Use CORSMiddleware
import annif.registry
Expand All @@ -54,7 +56,11 @@ def create_cx_app(config_name: str | None = None) -> FlaskApp:
cxapp.add_api("annif.yaml") # validator_map=validator_map)

# add CORS support
# CORS(cxapp.app)
cxapp.add_middleware(
CORSMiddleware,
position=MiddlewarePosition.BEFORE_EXCEPTION,
allow_origins=["*"],
)

if cxapp.app.config["INITIALIZE_PROJECTS"]:
annif.registry.initialize_projects(cxapp.app)
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ classifiers = [
[tool.poetry.dependencies]
python = ">=3.9,<3.12"

connexion = {version = ">=3.0.5", extras = ["flask","uvicorn", "swagger-ui"]}
connexion = {version = ">=3.0.5", extras = ["flask", "uvicorn", "swagger-ui"]}
click = "8.1.*"
click-log = "0.4.*"
joblib = "1.3.*"
Expand Down
16 changes: 10 additions & 6 deletions tests/test_openapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,11 @@
schema = schemathesis.from_path("annif/openapi/annif.yaml")


@schemathesis.check
def check_cors(response, case):
assert response.headers["access-control-allow-origin"] == "*"


@schema.parametrize()
@settings(max_examples=10)
def test_openapi_fuzzy(case, cxapp):
response = case.call_asgi(cxapp)
case.validate_response(response, additional_checks=(check_cors,))
case.validate_response(response)


@pytest.mark.slow
Expand All @@ -28,6 +23,15 @@ def test_openapi_fuzzy_target_dummy_fi(case, app):
case.validate_response(response)


def test_openapi_cors(app_client):
# test that the service supports CORS by simulating a cross-origin request
app_client.headers = {"Origin": "http://somedomain.com"}
req = app_client.get(
"http://localhost:8000/v1/projects",
)
assert req.headers["access-control-allow-origin"] == "*"


def test_openapi_list_projects(app_client):
req = app_client.get("http://localhost:8000/v1/projects")
assert req.status_code == 200
Expand Down

0 comments on commit beac55c

Please sign in to comment.