Skip to content

Commit

Permalink
fix: Logging middleware accepts TestClient without scope["client"]
Browse files Browse the repository at this point in the history
Since PR encode/starlette#2377, we can no longer expect
scope["client"] to return a tuple.
  • Loading branch information
torarvid committed Jan 12, 2024
1 parent 1b8d688 commit 8c79aff
Showing 1 changed file with 5 additions and 3 deletions.
8 changes: 5 additions & 3 deletions troncos/contrib/asgi/logging/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,18 @@ def __init__(
) -> None:
self._list: list[tuple[bytes, bytes]] = list(scope["headers"])

def add_client(self, client: tuple[str, int]) -> None:
def add_client(self, client: tuple[str, int] | None) -> None:
"""
The client IP is not stored in the ASGI headers by default.
Add the client ip to make sure we use it as a fallback if no
proxy headers are set.
"""
host = client[0] if client else "<no-host>"
port = client[1] if client else 0
self._list.append(
(
"REMOTE_ADDR".encode("latin-1"),
f"{client[0]}:{client[1]}".encode("latin-1"),
f"{host}:{port}".encode("latin-1"),
)
)

Expand Down Expand Up @@ -109,7 +111,7 @@ async def __call__(
ipware = IpWare()

headers = Headers(scope=scope)
headers.add_client(scope["client"])
headers.add_client(scope.get("client"))

client_ip, _ = ipware.get_client_ip(cast(dict[str, str], headers))

Expand Down

0 comments on commit 8c79aff

Please sign in to comment.