Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 4 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,21 +26,19 @@ import typesense


async def main() -> None:
client = typesense.AsyncClient({
async with typesense.AsyncClient({
"api_key": "abcd",
"nodes": [{"host": "localhost", "port": "8108", "protocol": "http"}],
"connection_timeout_seconds": 2,
})

print(await client.collections.retrieve())
await client.api_call.aclose()
}) as client:
print(await client.collections.retrieve())


if __name__ == "__main__":
asyncio.run(main())
```

See `examples/async_collection_operations.py` for a fuller async walkthrough.
See `examples/async_collection_operations.py` for a fuller async walkthrough. Note that if you pass a caller-supplied `http_client`, `AsyncClient` (and `Client`) leaves it open when exiting the context manager or calling `aclose()`/`close()`, so you are responsible for closing it.

## Streaming document exports

Expand Down
8 changes: 2 additions & 6 deletions examples/async_collection_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@


async def main() -> None:
client = typesense.AsyncClient(
async with typesense.AsyncClient(
{
"api_key": "xyz",
"nodes": [
Expand All @@ -24,9 +24,7 @@ async def main() -> None:
],
"connection_timeout_seconds": 2,
}
)

try:
) as client:
# Drop pre-existing collection if any
try:
await client.collections["books"].delete()
Expand Down Expand Up @@ -188,8 +186,6 @@ async def main() -> None:
# Drop the collection
drop_response = await client.collections["books"].delete()
print(drop_response)
finally:
await client.api_call.aclose()


if __name__ == "__main__":
Expand Down
8 changes: 2 additions & 6 deletions examples/async_conversation_streaming.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ async def main() -> None:
documents_collection = f"streaming_docs_{run_id}"
model_id = f"streaming_model_{run_id}"

client = typesense.AsyncClient(
async with typesense.AsyncClient(
{
"api_key": typesense_api_key,
"nodes": [
Expand All @@ -45,9 +45,7 @@ async def main() -> None:
],
"connection_timeout_seconds": 10,
}
)

try:
) as client:
await client.collections.create(
{
"name": history_collection,
Expand Down Expand Up @@ -139,8 +137,6 @@ def on_complete(response: SearchResponse[typing.Any]) -> None:
"stream_config": stream_config,
}
)
finally:
await client.api_call.aclose()


if __name__ == "__main__":
Expand Down
68 changes: 33 additions & 35 deletions examples/async_export_streaming.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,48 +13,46 @@


async def main() -> None:
client = typesense.AsyncClient(
async with typesense.AsyncClient(
{
"api_key": os.environ.get("TYPESENSE_API_KEY", "xyz"),
"nodes": [{"host": "localhost", "port": "8108", "protocol": "http"}],
"connection_timeout_seconds": 10,
}
)

await client.collections.create(
{
"name": COLLECTION,
"fields": [
{"name": "title", "type": "string"},
{"name": "year", "type": "int32"},
],
}
)

try:
documents = client.collections[COLLECTION].documents
await documents.import_(
[{"id": str(year), "title": f"Book {year}", "year": year} for year in range(2000, 2010)],
{"action": "create"},
) as client:
await client.collections.create(
{
"name": COLLECTION,
"fields": [
{"name": "title", "type": "string"},
{"name": "year", "type": "int32"},
],
}
)

# Read one document at a time. The stream is closed when the block ends,
# even if the loop stops early.
async with await documents.export_stream(
{"filter_by": "year:>=2005", "batch_size": 100},
) as stream:
async for line in stream:
print(json.loads(line)["title"])

# Count the bytes without keeping the export in memory.
size = 0
async with await documents.export_stream() as stream:
async for chunk in stream.aiter_bytes():
size += len(chunk)
print(f"Read {size} bytes")
finally:
await client.collections[COLLECTION].delete()
await client.api_call.aclose()
try:
documents = client.collections[COLLECTION].documents
await documents.import_(
[{"id": str(year), "title": f"Book {year}", "year": year} for year in range(2000, 2010)],
{"action": "create"},
)

# Read one document at a time. The stream is closed when the block ends,
# even if the loop stops early.
async with await documents.export_stream(
{"filter_by": "year:>=2005", "batch_size": 100},
) as stream:
async for line in stream:
print(json.loads(line)["title"])

# Count the bytes without keeping the export in memory.
size = 0
async with await documents.export_stream() as stream:
async for chunk in stream.aiter_bytes():
size += len(chunk)
print(f"Read {size} bytes")
finally:
await client.collections[COLLECTION].delete()


if __name__ == "__main__":
Expand Down
18 changes: 18 additions & 0 deletions src/typesense/async_/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"""

import sys
from types import TracebackType

from typing_extensions import deprecated

Expand Down Expand Up @@ -135,6 +136,23 @@ def __init__(
self.conversations_models = AsyncConversationsModels(self.api_call)
self.nl_search_models = AsyncNLSearchModels(self.api_call)

async def __aenter__(self) -> typing.Self:
"""Enter the context manager."""
return self

async def __aexit__(
self,
exc_type: typing.Optional[typing.Type[BaseException]],
exc_val: typing.Optional[BaseException],
exc_tb: typing.Optional[TracebackType],
) -> None:
"""Exit the context manager and close the HTTP client."""
await self.aclose()

async def aclose(self) -> None:
"""Close the underlying HTTP client, unless it was passed in by the caller."""
await self.api_call.aclose()

@property
@deprecated(
"AnalyticsV1 is deprecated on v30+. Use client.analytics instead.",
Expand Down
18 changes: 18 additions & 0 deletions src/typesense/sync/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"""

import sys
from types import TracebackType

from typing_extensions import deprecated

Expand Down Expand Up @@ -135,6 +136,23 @@ def __init__(
self.conversations_models = ConversationsModels(self.api_call)
self.nl_search_models = NLSearchModels(self.api_call)

def __enter__(self) -> typing.Self:
"""Enter the context manager."""
return self

def __exit__(
self,
exc_type: typing.Optional[typing.Type[BaseException]],
exc_val: typing.Optional[BaseException],
exc_tb: typing.Optional[TracebackType],
) -> None:
"""Exit the context manager and close the HTTP client."""
self.close()

def close(self) -> None:
"""Close the underlying HTTP client, unless it was passed in by the caller."""
self.api_call.close()

@property
@deprecated(
"AnalyticsV1 is deprecated on v30+. Use client.analytics instead.",
Expand Down
59 changes: 59 additions & 0 deletions tests/client_test.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
"""Tests for the Client class."""

import httpx

from tests.fixtures.document_fixtures import Companies
from tests.utils.object_assertions import assert_match_object, assert_object_lists_match
from typesense.async_.client import AsyncClient
from typesense.sync.client import Client
from typesense.configuration import ConfigDict

Expand Down Expand Up @@ -72,3 +75,59 @@ def test_retrieve_collection_actual_no_name(
collection = actual_client.typed_collection(model=Companies)

assert collection is not None


def test_client_close(fake_config_dict: ConfigDict) -> None:
"""Test that Client.close closes an owned HTTP client."""
client = Client(fake_config_dict)
assert client.api_call._client.is_closed is False
client.close()
assert client.api_call._client.is_closed is True


def test_client_context_manager(fake_config_dict: ConfigDict) -> None:
"""Test that Client closes its HTTP client when used as a context manager."""
with Client(fake_config_dict) as client:
assert client.api_call._client.is_closed is False
assert client.api_call._client.is_closed is True


def test_client_does_not_close_external_http_client(
fake_config_dict: ConfigDict,
) -> None:
"""Test that Client.close does not close a caller-supplied http_client."""
external_client = httpx.Client()
try:
with Client(fake_config_dict, http_client=external_client) as client:
assert client.api_call._client is external_client
assert external_client.is_closed is False
finally:
external_client.close()


async def test_async_client_aclose(fake_config_dict: ConfigDict) -> None:
"""Test that AsyncClient.aclose closes an owned HTTP client."""
client = AsyncClient(fake_config_dict)
assert client.api_call._client.is_closed is False
await client.aclose()
assert client.api_call._client.is_closed is True


async def test_async_client_context_manager(fake_config_dict: ConfigDict) -> None:
"""Test that AsyncClient closes its HTTP client when used as an async context manager."""
async with AsyncClient(fake_config_dict) as client:
assert client.api_call._client.is_closed is False
assert client.api_call._client.is_closed is True


async def test_async_client_does_not_close_external_http_client(
fake_config_dict: ConfigDict,
) -> None:
"""Test that AsyncClient.aclose does not close a caller-supplied http_client."""
external_client = httpx.AsyncClient()
try:
async with AsyncClient(fake_config_dict, http_client=external_client) as client:
assert client.api_call._client is external_client
assert external_client.is_closed is False
finally:
await external_client.aclose()
Loading