Skip to content
Discussion options

You must be logged in to vote

The reason the response.connection approach is flaky is that aiohttp hands the connection back to the pool the moment the body reaches EOF. For a short response that happens inside session.request(...), so by the time you reach the async with block response.connection is already None — on 3.14 it's None even for larger bodies, so it's not something you can lean on.

The reliable place to read it is the connector, not the response. TCPConnector.connect() runs for every request — including ones served from a reused pooled connection — and the transport is always live there. Subclass it, read the peername, and stash it in a ContextVar:

import contextvars, aiohttp

peer_ip: contextvars.ContextVar

Replies: 2 comments 2 replies

Comment options

You must be logged in to vote
2 replies
@vkruglik-aka
Comment options

@Dreamsorcerer
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by vkruglik-aka
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
4 participants