Skip to content

Instantly share code, notes, and snippets.

@praba230890
Created October 4, 2022 10:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save praba230890/339e1677eed055aeabca05db1e10543a to your computer and use it in GitHub Desktop.
Save praba230890/339e1677eed055aeabca05db1e10543a to your computer and use it in GitHub Desktop.
_SessionRequestContextManager from Async HTTP Framework - Async context manager example
class _SessionRequestContextManager:
__slots__ = ("_coro", "_resp", "_session")
def __init__(
self,
coro: Coroutine["asyncio.Future[Any]", None, ClientResponse],
session: ClientSession,
) -> None:
self._coro = coro
self._resp: Optional[ClientResponse] = None
self._session = session
async def __aenter__(self) -> ClientResponse:
try:
self._resp = await self._coro
except BaseException:
await self._session.close()
raise
else:
return self._resp
async def __aexit__(
self,
exc_type: Optional[Type[BaseException]],
exc: Optional[BaseException],
tb: Optional[TracebackType],
) -> None:
assert self._resp is not None
self._resp.close()
await self._session.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment