Skip to content

Commit e85715a

Browse files
authored
Support Starlette/FastAPI app.host (#4157)
In Starlette/FastAPI you're able to create subapps. When using `transaction_style="url"` in our integration, this would throw an exception because we try to access `route.path` to determine the transaction name, but `Host` routes have no `path` attribute. Closes #2631
1 parent 5dcda1d commit e85715a

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

sentry_sdk/integrations/starlette.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -693,7 +693,11 @@ def _transaction_name_from_router(scope):
693693
for route in router.routes:
694694
match = route.matches(scope)
695695
if match[0] == Match.FULL:
696-
return route.path
696+
try:
697+
return route.path
698+
except AttributeError:
699+
# routes added via app.host() won't have a path attribute
700+
return scope.get("path")
697701

698702
return None
699703

tests/integrations/fastapi/test_fastapi.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -682,3 +682,38 @@ async def _error():
682682
client.get("/error")
683683

684684
assert len(events) == int(expected_error)
685+
686+
687+
@pytest.mark.parametrize("transaction_style", ["endpoint", "url"])
688+
def test_app_host(sentry_init, capture_events, transaction_style):
689+
sentry_init(
690+
traces_sample_rate=1.0,
691+
integrations=[
692+
StarletteIntegration(transaction_style=transaction_style),
693+
FastApiIntegration(transaction_style=transaction_style),
694+
],
695+
)
696+
697+
app = FastAPI()
698+
subapp = FastAPI()
699+
700+
@subapp.get("/subapp")
701+
async def subapp_route():
702+
return {"message": "Hello world!"}
703+
704+
app.host("subapp", subapp)
705+
706+
events = capture_events()
707+
708+
client = TestClient(app)
709+
client.get("/subapp", headers={"Host": "subapp"})
710+
711+
assert len(events) == 1
712+
713+
(event,) = events
714+
assert "transaction" in event
715+
716+
if transaction_style == "url":
717+
assert event["transaction"] == "/subapp"
718+
else:
719+
assert event["transaction"].endswith("subapp_route")

0 commit comments

Comments
 (0)