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
1 change: 1 addition & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
### Removed

* Removed the Filter Extension depenency from `AggregationExtensionPostRequest` and `AggregationExtensionGetRequest` [#716](https://github.com/stac-utils/stac-fastapi/pull/716)
* Removed `add_middleware` method in `StacApi` object and let starlette handle the middleware stack creation [721](https://github.com/stac-utils/stac-fastapi/pull/721)

## [3.0.0a3] - 2024-06-13

Expand Down
7 changes: 1 addition & 6 deletions stac_fastapi/api/stac_fastapi/api/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -439,11 +439,6 @@ def add_route_dependencies(
"""
return add_route_dependencies(self.app.router.routes, scopes, dependencies)

def add_middleware(self, middleware: Middleware):
"""Add a middleware class to the application."""
self.app.user_middleware.insert(0, middleware)
self.app.middleware_stack = self.app.build_middleware_stack()

def __attrs_post_init__(self):
"""Post-init hook.

Expand Down Expand Up @@ -484,7 +479,7 @@ def __attrs_post_init__(self):

# add middlewares
for middleware in self.middlewares:
self.add_middleware(middleware)
self.app.user_middleware.insert(0, middleware)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vincentsarago why use the internal user_middleware list here, and not just use add_middleware? Do we need to add middleware after a call is made to the FastAPI app, so you're trying to avoid an error with registering middleware after the initialization? That seems like it might not be a good pattern, to register middleware after initialization; if we aren't supporting that, thne self.app.add_middleware(middleware) seems better here.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good call, let's use self.app.add_middleware

🙏 thanks @lossyrob

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ohhhh I see why we can't use starlette's add_middleware.

The add_middleware method expect a list of Callable + arguments (which will be turned into Middleware object) https://github.com/encode/starlette/blob/5a1bec33f8d6a669a3670f51034de83292d19408/starlette/applications.py#L134-L142

But the StacApi.middlewares is a list of Middleware objects so we need to insert them into the user_middleware list ourself.

That's said, I think it would be good to raise the same error from starlette https://github.com/encode/starlette/blob/5a1bec33f8d6a669a3670f51034de83292d19408/starlette/applications.py#L140-L141


# customize route dependencies
for scopes, dependencies in self.route_dependencies:
Expand Down
30 changes: 30 additions & 0 deletions stac_fastapi/api/tests/test_middleware.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from unittest import mock

import pytest
from fastapi import Request
from fastapi.responses import JSONResponse
from starlette.applications import Starlette
from starlette.testclient import TestClient

Expand Down Expand Up @@ -166,3 +168,31 @@ def test_cors_middleware(test_client):
resp = test_client.get("/_mgmt/ping", headers={"Origin": "http://netloc"})
assert resp.status_code == 200
assert resp.headers["access-control-allow-origin"] == "*"


def test_middleware_stack():
stac_api = StacApi(
settings=ApiSettings(), client=mock.create_autospec(BaseCoreClient)
)

def exception_handler(request: Request, exc: Exception) -> JSONResponse:
return JSONResponse(
status_code=400,
content={"customerrordetail": "yoo", "body": "yo"},
)

class CustomException(Exception):
"Custom Exception"

pass

stac_api.app.add_exception_handler(CustomException, exception_handler)

@stac_api.app.get("/error")
def error_endpoint():
raise CustomException("got you!")

with TestClient(stac_api.app) as client:
resp = client.get("/error")
assert resp.status_code == 400
assert resp.json()["customerrordetail"] == "yoo"