Skip to main content

Ayncio Client for Azure Cosmos DB

Project description

aio-cosmos

Asyncio SDK for Azure Cosmos DB. This library is intended to be a very thin asyncio wrapper around the Azure Comsos DB Rest API. It is not intended to have feature parity with the Microsoft Azure SDKs but to provide async versions of the most commonly used interfaces.

Feature Support

Databases

✅ List
✅ Create
✅ Delete

Containers

✅ Create
✅ Delete

Documents

✅ Create Single
✅ Create Concurrent Multiple
✅ Delete
✅ Get
✅ Query

Limitations

The library currently only supports Session level consistency, this may change in the future. For concurrent writes the maximum concurrency level is based on a maximum of 100 concurrent connections from the underlying aiohttp library. This may be exposed to the as a client setting in a future version.

Sessions are managed automatically for document operations. The session token is returned in the result so it is possible to manage sessions manually by providing this value in session_token to the appropriate methods. This facilitates sending the token value back to an end client in a session cookie so that writes and reads can maintain consistency across multiple instances of Cosmos.

There is currently no retry policy on failed connections/broken connections and this must be entirely managed by the end user code. This may be implemented in the future

Installation

pip install aio-cosmos

Usage

Client Setup and Basic Usage

The client can be instantiated using either the context manager as below or directly using the CosmosClient class. If using the CosmosClient class directly the user is responsible for calling the .connect() and .close() methods to ensure the client is boot-strapped and resources released at the appropriate times.

from aio_cosmos.client import get_client

async with get_client(endpoint, key) as client:
    await client.create_database('database-name')
    await client.create_container('database-name', 'container-name', '/partition_key_document_path')
    doc_id = str(uuid4())
    res = await client.create_document(f'database-name', 'container-name',
                                       {'id': doc_id, 'partition_key_document_path': 'Account-1', 'description': 'tax surcharge'}, partition_key="Account-1")

Querying Documents

Documents can be queried using the query_documents method on the client. This method returns an AsyncGenerator and should be used in an async for statement as below. The generator automatically handles paging for large datasets. If you don't wish to iterate through the results use a list comprehension to collate all of them.

async for doc in client.query_documents(f'database-name', 'container-name',
                                        query="select * from r where r.account = 'Account-1'",
                                        partition_key="Account-1"):
    print(f'doc returned by query: {doc}')

Concurrent Writes / Multiple Documents

The client provides the ability to issue concurrent document writes using asyncio/aiohttp. Each document is represented by a tuple of (document, partition key value) as below.

docs = [
    ({'id': str(uuid4()), 'account': 'Account-1', 'description': 'invoice paid'}, 'Account-1'),
    ({'id': str(uuid4()), 'account': 'Account-1', 'description': 'VAT remitted'}, 'Account-1'),
    ({'id': str(uuid4()), 'account': 'Account-1', 'description': 'interest paid'}, 'Account-1'),
    ({'id': str(uuid4()), 'account': 'Account-2', 'description': 'annual fees'}, 'Account-2'),
    ({'id': str(uuid4()), 'account': 'Account-2', 'description': 'commission'}, 'Account-2'),
]

res = await client.create_documents(f'database-name', 'container-name', docs)

Results

Results are returned in a dictionary with the following format:

{
    'status': str,
    'code': int,
    'session_token': Optional[str],
    'error': Optional[str],
    'data': Union[dict,list]
}
  • status will be either 'ok' or 'failed'
  • code is the integer HTTP response code
  • session_token is the string session code vector returned by Cosmos
  • error is a string error message to provide context to a failed status
  • data is the direct JSON response from Cosmos and will contain any error information in the case of failed operations

Note, to see an error return in the above format you must pass raise_on_failure=False to the client constructor.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

aio-cosmos-0.2.4.tar.gz (13.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

aio_cosmos-0.2.4-py3-none-any.whl (14.3 kB view details)

Uploaded Python 3

File details

Details for the file aio-cosmos-0.2.4.tar.gz.

File metadata

  • Download URL: aio-cosmos-0.2.4.tar.gz
  • Upload date:
  • Size: 13.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.11 CPython/3.7.1 Darwin/20.6.0

File hashes

Hashes for aio-cosmos-0.2.4.tar.gz
Algorithm Hash digest
SHA256 f4351b1b7f1db9d7fef8dbd44e7b88386201462703f1c40b1c8613190afae3cb
MD5 803f7b4341e7fce59cd9ec29e67f5407
BLAKE2b-256 2123cb4897681955c9121c18e4fc1e5cb9fd21e8fd6e03d1ebd7b9a93e7062b3

See more details on using hashes here.

File details

Details for the file aio_cosmos-0.2.4-py3-none-any.whl.

File metadata

  • Download URL: aio_cosmos-0.2.4-py3-none-any.whl
  • Upload date:
  • Size: 14.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.11 CPython/3.7.1 Darwin/20.6.0

File hashes

Hashes for aio_cosmos-0.2.4-py3-none-any.whl
Algorithm Hash digest
SHA256 0eb460a943f334524512e4b6b285eb4c4f815fe86bf16a2d522a99b9717e83a7
MD5 55b1eb21bcd9d9decfcbc962061fdcd3
BLAKE2b-256 089652792994dc1d6d5ad09c75d17bc9ed07fb4c8d9103a0c952ea116c29a6a3

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page