188188class _AsyncBoundSessionContext :
189189 """Context manager returned by AsyncClientSession.bind() that manages bound state."""
190190
191- def __init__ (self , session : AsyncClientSession ) -> None :
191+ def __init__ (self , session : AsyncClientSession , end_session : bool ) -> None :
192192 self ._session = session
193193 self ._session_token : Optional [Token [AsyncClientSession ]] = None
194+ self ._end_session = end_session
194195
195196 async def __aenter__ (self ) -> AsyncClientSession :
196197 self ._session_token = _SESSION .set (self ._session ) # type: ignore[assignment]
@@ -200,6 +201,8 @@ async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
200201 if self ._session_token :
201202 _SESSION .reset (self ._session_token ) # type: ignore[arg-type]
202203 self ._session_token = None
204+ if self ._end_session :
205+ await self ._session .end_session ()
203206
204207
205208class SessionOptions :
@@ -567,12 +570,14 @@ def _check_ended(self) -> None:
567570 if self ._server_session is None :
568571 raise InvalidOperation ("Cannot use ended session" )
569572
570- def bind (self ) -> _AsyncBoundSessionContext :
573+ def bind (self , end_session : bool = False ) -> _AsyncBoundSessionContext :
571574 """Bind this session so it is implicitly passed to all database operations within the returned context.
572575
576+ :param end_session: Whether to end the session on exiting the returned context. Defaults to False.
577+
573578 .. versionadded:: 4.17
574579 """
575- return _AsyncBoundSessionContext (self )
580+ return _AsyncBoundSessionContext (self , end_session )
576581
577582 async def __aenter__ (self ) -> AsyncClientSession :
578583 return self
0 commit comments