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
Coronavirus whatsapp chatbot to give real time info on covid

Covy Developed a coronavirus whatsapp chatbot which gives case counts in a particular district, city, state or country. It also predicts future cases

Devinco (Rachit) 0 Oct 03, 2021
可基于【腾讯云函数】/【GitHub Actions】/【Docker】的每日签到脚本(支持多账号使用)签到列表: |爱奇艺|全民K歌|腾讯视频|有道云笔记|网易云音乐|一加手机社区官方论坛|百度贴吧|Bilibili|V2EX|咔叽网单|什么值得买|AcFun|天翼云盘|WPS|吾爱破解|芒果TV|联通营业厅|Fa米家|小米运动|百度搜索资源平台|每日天气预报|每日一句|哔咔漫画|和彩云|智友邦|微博|CSDN|王者营地|

每日签到集合 基于【腾讯云函数】/【GitHub Actions】/【Docker】的每日签到脚本 支持多账号使用 特别声明: 本仓库发布的脚本及其中涉及的任何解锁和解密分析脚本,仅用于测试和学习研究,禁止用于商业用途,不能保证其合法性,准确性,完整性和有效性,请根据情况自行判断。

87 Nov 12, 2022
Powerful Ethereum Smart-Contract Toolkit

Heimdall Heimdall is an advanced and modular smart-contract toolkit which aims to make dealing with smart contracts on EVM based chains easier. Instal

Jonathan Becker 69 Dec 26, 2022
OpenSea Python Bot coded purely in Python3.

OpenSea Python Bot coded purely in Python3. It utilises everything from OpenSea API to continuously monitor NFT's. It can be used to snipe or monitor if something falls below floor value.

OpenSea Elite Sniper 20 Dec 29, 2021
Latest Open Source Code for Playing Music in Telegram Video Chat. Made with Pyrogram and Pytgcalls 💖

MusicPlayer_TG Latest Open Source Code for Playing Music in Telegram Video Chat. Made with Pyrogram and Pytgcalls 💖 Requirements 📝 FFmpeg NodeJS nod

Abhijith Sudhakaran 2 Feb 04, 2022
Dante, my discord bot. Open source project in development and not optimized for other filesystems, install and setup script in development

DanteMode (In private development for ~6 months) Dante, my discord bot. Open source project in development and not optimized for other filesystems, in

2 Nov 05, 2021
Multipurpose Discord bot hosted on replit.com

RockyBot Multipurpose Discord bot hosted on https://replit.com/ Installing Dependencies Install poetry through pip: pip install poetry Then simply exe

Rocky 2 May 18, 2022
Univerity-student oriented (lithuanian) discord bot

Univerity-student oriented (lithuanian) discord bot

3 Nov 30, 2021
Official python API for Phish.AI public and private API to detect zero-day phishing websites

phish-ai-api Summary Official python API for Phish.AI public and private API to detect zero-day phishing websites How it Works (TLDR) Essentially we h

Phish.AI 168 May 17, 2022
This package accesses nitrotype's official api along with its unofficial user api

NitrotypePy This package accesses nitrotype's official api along with its unofficial user api. Currently still in development. Install To install, run

The Moon That Rises 2 Sep 04, 2022
S3-cleaner - A Python script attempts to delete the all objects/delete markers/versions from specific S3 bucket

Remove All Objects From S3 Bucket This Python script attempts to delete the all

9 Jan 27, 2022
Bot interpretation of the carbon.now.sh site

📒 Source code of the @PicodeBot 🧸 Developer: @hoosnick Run $ git clone https://github.com/hoosnick/picodebot.git $ pip install -r requirements.txt P

Husniddin Murodov 13 Oct 02, 2022
Repository to access information of stocks in Bombay Stock Exchange.

BSE Repository to access information of stocks in Bombay Stock Exchange. The code in this repository uses BSE API and conclusions made using the code

1 Nov 13, 2021
Powerful Telegram Maintained UserBot in Telethon

Fire-X UserBot The Awaited Bot Fire-X userbot The Most Powerful Telegram Userbot. This Userbot is Safe to use in Your Telegram Account. It is not like

22 Oct 21, 2022
Search twitter by address.

Twitter Geolocate Twitter Geolocation is a console app that generates twitter search querries for a certain geolocation and opens them in your standar

David J. Kowalk 28 Dec 06, 2022
⚡ Yuriko Robot ⚡ - A Powerful, Smart And Simple Group Manager Written with AioGram , Pyrogram and Telethon

⚡ Yuriko Robot ⚡ - A Powerful, Smart And Simple Group Manager Written with AioGram , Pyrogram and Telethon

Øғғɪᴄɪᴀʟ Ⱡᴏɢ [₳ғᴋ] 1 Apr 01, 2022
send sms via grafana alert webhook

notifier fire alarm What does this project do: the aim of this project is to send alarm notification from grafana alert manager via kavenegar api. sta

Ali Soltani 4 Oct 20, 2021
Pythonic and easy iCalendar library (rfc5545)

ics.py 0.8.0-dev : iCalendar for Humans Original repository (GitHub) - Bugtracker and issues (GitHub) - PyPi package (ics) - Documentation (Read The D

ics.py 513 Jan 02, 2023
A client interface for Scrapinghub's API

Client interface for Scrapinghub API The scrapinghub is a Python library for communicating with the Scrapinghub API. Requirements Python 2.7 or above

Scrapinghub 184 Sep 28, 2022
A VCVideoPlayer Bot for Telegram made with 💞 By @ProErrorXD

VC Video Player How To Host ✨ Heroku Deploy ✨ The easiest way to deploy this Bot is via Heroku. Credit 🔥 |🇮🇳 Louis |🇮🇳 Sammy |🇮🇳 Blaze Marsha

丂ムᄊᄊƳ 95 May 17, 2022