mirror of
https://github.com/ollama/ollama-python.git
synced 2026-01-13 21:57:16 +08:00
feat: add close() method and context manager support to Client and AsyncClient
- Add close() method to Client and AsyncClient for explicit resource cleanup - Implement __enter__/__exit__ for Client to support context manager usage - Implement __aenter__/__aexit__ for AsyncClient to support async context manager usage - Allows usage: with Client() as client: ... - Allows usage: async with AsyncClient() as client: ... Closes #532
This commit is contained in:
parent
9ddd5f0182
commit
6b8484ca42
@ -124,6 +124,19 @@ class Client(BaseClient):
|
||||
def __init__(self, host: Optional[str] = None, **kwargs) -> None:
|
||||
super().__init__(httpx.Client, host, **kwargs)
|
||||
|
||||
def close(self) -> None:
|
||||
"""Close the underlying HTTP client and release resources."""
|
||||
self._client.close()
|
||||
|
||||
def __enter__(self):
|
||||
"""Support usage as a context manager."""
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
"""Ensure the client is closed when exiting the context."""
|
||||
self.close()
|
||||
return False
|
||||
|
||||
def _request_raw(self, *args, **kwargs):
|
||||
try:
|
||||
r = self._client.request(*args, **kwargs)
|
||||
@ -686,6 +699,19 @@ class AsyncClient(BaseClient):
|
||||
def __init__(self, host: Optional[str] = None, **kwargs) -> None:
|
||||
super().__init__(httpx.AsyncClient, host, **kwargs)
|
||||
|
||||
async def close(self) -> None:
|
||||
"""Close the underlying HTTP client and release resources."""
|
||||
await self._client.aclose()
|
||||
|
||||
async def __aenter__(self):
|
||||
"""Support usage as an async context manager."""
|
||||
return self
|
||||
|
||||
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
||||
"""Ensure the client is closed when exiting the async context."""
|
||||
await self.close()
|
||||
return False
|
||||
|
||||
async def _request_raw(self, *args, **kwargs):
|
||||
try:
|
||||
r = await self._client.request(*args, **kwargs)
|
||||
|
||||
Loading…
Reference in New Issue
Block a user