Asyncio SDK for Azure Cosmos DB

Overview

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.

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 of 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 either the data or error return of the operation from Cosmos

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

You might also like...
The successor of GeoSnipe, a pythonic Minecraft username sniper based on AsyncIO.
The successor of GeoSnipe, a pythonic Minecraft username sniper based on AsyncIO.

OneSnipe The successor of GeoSnipe, a pythonic Minecraft username sniper based on AsyncIO. Documentation View Documentation Features • Mojang & Micros

An asyncio Python wrapper around the Discord API, forked off of Rapptz's Discord.py.

Novus A modern, easy to use, feature-rich, and async ready API wrapper for Discord written in Python. A full fork of Rapptz's Discord.py library, with

Asynchronous and also synchronous non-official QvaPay client for asyncio and Python language.
Asynchronous and also synchronous non-official QvaPay client for asyncio and Python language.

Asynchronous and also synchronous non-official QvaPay client for asyncio and Python language. This library is still under development, the interface could be changed.

asyncio client for Deta Cloud

aiodeta Unofficial client for Deta Clound Install pip install aiodeta Supported functionality Deta Base Deta Drive Decorator for cron tasks Examples i

Spore REST API asyncio client

Spore REST API asyncio client

AWS SDK for Python

Boto3 - The AWS SDK for Python Boto3 is the Amazon Web Services (AWS) Software Development Kit (SDK) for Python, which allows Python developers to wri

Python SDK for Facebook's Graph API

Facebook Python SDK This client library is designed to support the Facebook Graph API and the official Facebook JavaScript SDK, which is the canonical

Box SDK for Python

Box Python SDK Installing Getting Started Authorization Server-to-Server Auth with JWT Traditional 3-legged OAuth2 Other Auth Options Usage Documentat

The Official Dropbox API V2 SDK for Python
The Official Dropbox API V2 SDK for Python

The offical Dropbox SDK for Python. Documentation can be found on Read The Docs. Installation Create an app via the Developer Console. Install via pip

Comments
  • Upsert flag on create_document causes TypeError

    Upsert flag on create_document causes TypeError

    When using upsert=True on CosmosClient.create_document, a TypeError is thrown:

    >>> await client.create_document(database='my-db', container='my-container', partition_key='...', json={"id": "blah blah"}, upsert=True)
    

    Throws:

    Traceback (most recent call last):
      File "C:\python39\lib\concurrent\futures\_base.py", line 445, in result
        return self.__get_result()
      File "C:\python39\lib\concurrent\futures\_base.py", line 390, in __get_result
        raise self._exception
      File "<console>", line 1, in <module>
      File "[REDACTED]\.venv\lib\site-packages\aio_cosmos\client.py", line 223, in create_document
        async with self.session.post(f'{self._get_writable()}/dbs/{database}/colls/{container}/docs',
      File "[REDACTED]\.venv\lib\site-packages\aiohttp\client.py", line 1138, in __aenter__
        self._resp = await self._coro
      File "[REDACTED]\.venv\lib\site-packages\aiohttp\client.py", line 557, in _request
        resp = await req.send(conn)
      File "[REDACTED]\.venv\lib\site-packages\aiohttp\client_reqrep.py", line 669, in send
        await writer.write_headers(status_line, self.headers)
      File "[REDACTED]\.venv\lib\site-packages\aiohttp\http_writer.py", line 130, in write_headers
        buf = _serialize_headers(status_line, headers)
      File "aiohttp\_http_writer.pyx", line 132, in aiohttp._http_writer._serialize_headers
      File "aiohttp\_http_writer.pyx", line 109, in aiohttp._http_writer.to_str
    TypeError: Cannot serialize non-str key True
    

    We can currently work around this issue by passing in the boolean as a string (i.e. upsert='True') but the IDE raises warnings as the type hints expect a boolean.

    I think we just need to cast the upsert flag to a string in client.py

    opened by danarth 1
Releases(0.2.4)
Owner
Grant McDonald
Grant McDonald
Async boto3 with Autogenerated Data Classes

awspydk Async boto3 with Autogenerated JIT Data Classes Motivation This library is forked from an internal project that works with a lot of backend AW

1 Dec 05, 2021
MashaRobot : New Generation Telegram Group Manager Bot (🔸Fast 🔸Python🔸Pyrogram 🔸Telethon 🔸Mongo db )

MashaRobot Me On Telegram ✨ MASHA ✨ This is just a demo bot.. Don't try to add to your group.. Create your own bot How To Host The easiest way to depl

Mr Dark Prince 40 Oct 09, 2022
摩尔庄园手游脚本

摩尔庄园 BlueStacks 脚本 手游上线,情怀再起,但面对游戏中枯燥无味的每日任务和资源采集,你是否觉得肝疼呢? 本项目通过生成 BlueStacks 模拟器的宏脚本,帮助玩家护肝。 使用脚本请阅读 使用方式 和对应的 功能及说明 联系 Telegram 频道 @mole61 Telegram

WH-2099 43 Dec 16, 2022
A simple discord bot named atticus that sends you the timetable of your classes upon request

A simple discord bot named atticus that sends you the timetable of your classes upon request. Soon, it would you ping you before classes too!

Samhitha 3 Oct 13, 2022
An API that allows you to get full information about TikTok videos

TikTok-API An API that allows you to get full information about TikTok videos without using any third party sources and only the TikTok API. ##API onl

FC 13 Dec 20, 2021
Dashboard to monitor the performance of your Binance Futures account

futuresboard A python based scraper and dashboard to monitor the performance of your Binance Futures account. Note: A local sqlite3 database config/fu

86 Dec 29, 2022
An example of a chatbot with a number-based menu that can be used as a starting point for a project.

NumMenu Bot NumMenu Bot is an example chatbot showing a way to design a number-based menu assistant with Rasa. This type of bot is very useful on plat

Derguene 19 Nov 14, 2022
Lazy airdrop based on private temporary ids

LobsterDAO This uses a modified MerkleDistributor, which allows to issue a lazy airdrop using temporary IDs. In this example it uses Telegram chat_id

41 Sep 10, 2022
Python Wrapper for aztro - The Astrology API | Get Daily Horoscope 💫

PyAztro PyAztro is a client library for aztro written in Python. aztro provides horoscope info for sun signs such as Lucky Number, Lucky Color, Mood,

Sameer Kumar 30 Jan 08, 2023
Telegram Bot to save Posts or Files that can be Accessed via Special Links

OKAERI-FILE Bot Telegram untuk menyimpan Posting atau File yang dapat Diakses melalui Link Khusus. Jika Anda memerlukan tambahan module lagi dalam rep

Wahyusaputra 5 Aug 04, 2022
A light wrapper around FedEx's SOAP API.

Python FedEx SOAP API Module Author: Greg Taylor, Radek Wojcik Maintainer: Python FedEx Developers License: BSD Status: Stable What is it? A light wra

155 Dec 16, 2022
A python script fetches all your starred repositories from your GitHub account and clones them to your server so you will never lose important resources

A python script fetches all your starred repositories from your GitHub account and clones them to your server so you will never lose important resources

Ringo Hoffmann 27 Oct 01, 2022
A cs:go cheat/hack made in Python3.

Atomic 💖 Cheat for cs:go written in Python. Features. Glow Esp No Flash Bunny Hop Third Person To-Do. It is prefered to start the cheat when you are

Sofia 6 Feb 12, 2022
A Python Script to automate searching of available vaccination centers in the city and hence booking

Cowin Vaccine Availability Notifier Cowin Vaccine Availability Notifier takes your City or PIN code as an input and automatically notifies you via ema

Jayesh Padhiar 7 Sep 05, 2021
Instagram GiftShop Scam Killer

Instagram GiftShop Scam Killer A basic tool for Windows which kills acess to any giftshop scam from Instagram. Protect your Instagram account from the

1 Mar 31, 2022
Automate and Manage Telegram Channels

Channel Automation Bot @ChannelAutomateBot A star ⭐ from you means a lot to us! Telegram bot to automate and manage channels. Usage Deploy to Heroku T

Stark Bots 61 Dec 29, 2022
Powerful Telegram Members Scraping and Adding Toolkit

🔥 Genisys V2.1 Powerful Telegram Members Scraping and Adding Toolkit 🔻 Features 🔺 ADDS IN BULK[by user id, not by username] Scrapes and adds to pub

The Cryptonian 16 Mar 01, 2022
Random Geek Jokes REST API

Geek-Jokes A RESTful API to get random geek jokes written in Flask What is the Geek-Jokes-api? The Geek Jokes RESTful API lets you fetch a random geek

Sameer Kumar 84 Dec 15, 2022
MSE5050/7050 Materials Informatics course at the University of Utah

MaterialsInformatics MSE5050/7050 Materials Informatics course at the University of Utah This github repo contains coursework content such as class sl

41 Dec 30, 2022
Jupyter notebooks and AWS CloudFormation template to show how Hudi, Iceberg, and Delta Lake work

Modern Data Lake Storage Layers This repository contains supporting assets for my research in modern Data Lake storage layers like Apache Hudi, Apache

Damon P. Cortesi 25 Oct 31, 2022