Skip to content

Commit

Permalink
fix: client is potentially None
Browse files Browse the repository at this point in the history
  • Loading branch information
winstxnhdw committed Feb 27, 2024
1 parent 653f3f4 commit d024932
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 6 deletions.
11 changes: 6 additions & 5 deletions server/middlewares/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,22 +65,23 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send):
if scope['type'] != 'http':
return await self.app(scope, receive, send)

status_code = [500]
start_process_time = process_time()
status_code = [500]
user_agents = [v for k, v in scope['headers'] if k.lower() == b'user-agent']
user_agent = 'NIL' if not user_agents else user_agents[0].decode()
client = scope['client']
client_ip = 'NIL' if not client else client[0]

try:
await self.app(scope, receive, self.inner_send_factory(send, status_code))

finally:
user_agents = [v for k, v in scope['headers'] if k.lower() == b'user-agent']
user_agent = 'NIL' if not user_agents else user_agents[0].decode()

self.logger.info('[%s] [INFO] %d "%s %s" %s "%s" in %.4f ms',
strftime('%Y-%m-%d %H:%M:%S %z'),
status_code[0],
scope['method'],
scope['path'],
scope['client'][0],
client_ip,
user_agent,
(process_time() - start_process_time) * 1000
)
2 changes: 1 addition & 1 deletion server/typings/starlette/types.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ class Scope(TypedDict):
asgi: Mapping[str, str]
http_version: str
server: tuple[str, int]
client: tuple[str, int]
client: tuple[str, int] | None
scheme: Literal['http', 'https']
root_path: str
headers: list[tuple[bytes, bytes]]
Expand Down

0 comments on commit d024932

Please sign in to comment.