azure.cosmos.aio package¶
-
class
azure.cosmos.aio.
ContainerProxy
(client_connection: azure.cosmos.aio._cosmos_client_connection_async.CosmosClientConnection, database_link: str, id: str, properties: Optional[Dict[str, Any]] = None)[source]¶ An interface to interact with a specific DB Container.
This class should not be instantiated directly. Instead, use the
get_container_client()
method to get an existing container, or theDatabaseProxy()
method to create a new container.A container in an Azure Cosmos DB SQL API database is a collection of documents, each of which is represented as an Item.
- Variables
-
async
create_item
(body, **kwargs) → Dict[str, Any][source]¶ Create an item in the container.
To update or replace an existing item, use the
ContainerProxy.upsert_item()
method.- Parameters
body – A dict-like object representing the item to create.
- Keyword Arguments
pre_trigger_include – trigger id to be used as pre operation trigger.
post_trigger_include – trigger id to be used as post operation trigger.
indexing_directive – Indicate whether the document should be omitted from indexing.
enable_automatic_id_generation (bool) – Enable automatic id generation if no id present.
session_token (str) – Token for use with Session consistency.
initial_headers (dict[str,str]) – Initial headers to be sent as part of the request.
etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.
match_condition (MatchConditions) – The match condition to use upon the etag.
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
A dict representing the new item.
- Raises
CosmosHttpResponseError – Item with the given ID already exists.
- Return type
-
async
delete_conflict
(conflict, partition_key, **kwargs) → None[source]¶ Delete a specified conflict from the container.
If the conflict does not already exist in the container, an exception is raised.
- Parameters
conflict – The ID (name) or dict representing the conflict to be deleted.
partition_key – Partition key for the conflict to delete.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Raises
CosmosHttpResponseError – The conflict wasn’t deleted successfully.
CosmosResourceNotFoundError – The conflict does not exist in the container.
- Return type
-
async
delete_item
(item, partition_key, pre_trigger_include=None, post_trigger_include=None, **kwargs) → None[source]¶ Delete the specified item from the container.
If the item does not already exist in the container, an exception is raised.
- Parameters
item – The ID (name) or dict representing item to be deleted.
partition_key – Specifies the partition key value for the item.
pre_trigger_include – trigger id to be used as pre operation trigger.
post_trigger_include – trigger id to be used as post operation trigger.
- Keyword Arguments
session_token (str) – Token for use with Session consistency.
initial_headers (dict[str,str]) – Initial headers to be sent as part of the request.
etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.
match_condition (MatchConditions) – The match condition to use upon the etag.
response_hook (Callable) – A callable invoked with the response metadata.
- Raises
CosmosHttpResponseError – The item wasn’t deleted successfully.
CosmosResourceNotFoundError – The item does not exist in the container.
- Return type
-
list_conflicts
(max_item_count: Optional[int] = None, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ List all the conflicts in the container.
- Parameters
max_item_count – Max number of items to be returned in the enumeration operation.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
An AsyncItemPaged of conflicts (dicts).
- Return type
AsyncItemPaged[Dict[str, Any]]
-
query_conflicts
(query, parameters=None, partition_key=None, max_item_count=None, **kwargs) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ Return all conflicts matching a given query.
- Parameters
query – The Azure Cosmos DB SQL query to execute.
parameters – Optional array of parameters to the query. Ignored if no query is provided.
partition_key – Specifies the partition key value for the item. If none is passed in, a cross partition query will be executed.
max_item_count – Max number of items to be returned in the enumeration operation.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
An AsyncItemPaged of conflicts (dicts).
- Return type
AsyncItemPaged[Dict[str, Any]]
-
query_items
(query, parameters=None, partition_key=None, max_item_count=None, enable_scan_in_query=None, populate_query_metrics=None, **kwargs) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ Return all results matching the given query.
You can use any value for the container name in the FROM clause, but often the container name is used. In the examples below, the container name is “products,” and is aliased as “p” for easier referencing in the WHERE clause.
- Parameters
query – The Azure Cosmos DB SQL query to execute.
parameters – Optional array of parameters to the query. Each parameter is a dict() with ‘name’ and ‘value’ keys. Ignored if no query is provided.
partition_key – Specifies the partition key value for the item. If none is provided, a cross-partition query will be executed
max_item_count – Max number of items to be returned in the enumeration operation.
enable_scan_in_query – Allow scan on the queries which couldn’t be served as indexing was opted out on the requested paths.
populate_query_metrics – Enable returning query metrics in response headers.
- Keyword Arguments
Provisional keyword argument max_integrated_cache_staleness_in_ms :keyword int max_integrated_cache_staleness_in_ms: The max cache staleness for the integrated cache in milliseconds.
For accounts configured to use the integrated cache, using Session or Eventual consistency, responses are guaranteed to be no staler than this value.
- Returns
An AsyncItemPaged of items (dicts).
- Return type
AsyncItemPaged[Dict[str, Any]]
Example:
import json async for item in container.query_items( query='SELECT * FROM products p WHERE p.productModel <> "DISCONTINUED"', enable_cross_partition_query=True, ): print(json.dumps(item, indent=True))
discontinued_items = container.query_items( query='SELECT * FROM products p WHERE p.productModel = @model AND p.productName="Widget"', parameters=[dict(name="@model", value="DISCONTINUED")], ) async for item in discontinued_items: print(json.dumps(item, indent=True))
-
query_items_change_feed
(partition_key_range_id=None, is_start_from_beginning=False, continuation=None, max_item_count=None, **kwargs) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ Get a sorted list of items that were changed, in the order in which they were modified.
- Parameters
partition_key_range_id – ChangeFeed requests can be executed against specific partition key ranges. This is used to process the change feed in parallel across multiple consumers.
partition_key – partition key at which ChangeFeed requests are targetted.
is_start_from_beginning – Get whether change feed should start from beginning (true) or from current (false). By default it’s start from current (false).
continuation – e_tag value to be used as continuation for reading change feed.
max_item_count – Max number of items to be returned in the enumeration operation.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
An AsyncItemPaged of items (dicts).
- Return type
AsyncItemPaged[Dict[str, Any]]
-
async
read
(populate_partition_key_range_statistics=None, populate_quota_info=None, **kwargs) → Dict[str, Any][source]¶ Read the container properties.
- Parameters
populate_partition_key_range_statistics – Enable returning partition key range statistics in response headers.
populate_quota_info – Enable returning collection storage quota information in response headers.
- Keyword Arguments
- Raises
CosmosHttpResponseError – Raised if the container couldn’t be retrieved. This includes if the container does not exist.
- Returns
Dict representing the retrieved container.
- Return type
-
read_all_items
(max_item_count=None, **kwargs) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ List all the items in the container.
- Parameters
max_item_count – Max number of items to be returned in the enumeration operation.
- Keyword Arguments
Provisional keyword argument max_integrated_cache_staleness_in_ms :keyword int max_integrated_cache_staleness_in_ms: The max cache staleness for the integrated cache in milliseconds.
For accounts configured to use the integrated cache, using Session or Eventual consistency, responses are guaranteed to be no staler than this value.
- Returns
An AsyncItemPaged of items (dicts).
- Return type
AsyncItemPaged[Dict[str, Any]]
-
async
read_conflict
(conflict, partition_key, **kwargs) → Dict[str, Any][source]¶ Get the conflict identified by conflict.
- Parameters
conflict – The ID (name) or dict representing the conflict to retrieve.
partition_key – Partition key for the conflict to retrieve.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
A dict representing the retrieved conflict.
- Raises
CosmosHttpResponseError – The given conflict couldn’t be retrieved.
- Return type
-
async
read_item
(item, partition_key, **kwargs) → Dict[str, Any][source]¶ Get the item identified by item.
- Parameters
item – The ID (name) or dict representing item to retrieve.
partition_key – Partition key for the item to retrieve.
- Keyword Arguments
Provisional keyword argument max_integrated_cache_staleness_in_ms :keyword int max_integrated_cache_staleness_in_ms: The max cache staleness for the integrated cache in milliseconds.
For accounts configured to use the integrated cache, using Session or Eventual consistency, responses are guaranteed to be no staler than this value.
- Returns
Dict representing the item to be retrieved.
- Raises
CosmosHttpResponseError – The given item couldn’t be retrieved.
- Return type
Example:
item = await container.read_item("item2", partition_key="Widget") item["productModel"] = "DISCONTINUED" updated_item = await container.upsert_item(item)
-
async
read_offer
(**kwargs: Any) → azure.cosmos.offer.Offer[source]¶ Read the Offer object for this container.
If no Offer already exists for the container, an exception is raised.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
Offer for the container.
- Raises
CosmosHttpResponseError – No offer exists for the container or the offer could not be retrieved.
- Return type
-
async
replace_item
(item, body, pre_trigger_include=None, post_trigger_include=None, **kwargs) → Dict[str, Any][source]¶ Replaces the specified item if it exists in the container.
If the item does not already exist in the container, an exception is raised.
- Parameters
item – The ID (name) or dict representing item to be replaced.
body – A dict-like object representing the item to replace.
pre_trigger_include – trigger id to be used as pre operation trigger.
post_trigger_include – trigger id to be used as post operation trigger.
- Keyword Arguments
session_token (str) – Token for use with Session consistency.
initial_headers (dict[str,str]) – Initial headers to be sent as part of the request.
etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.
match_condition (MatchConditions) – The match condition to use upon the etag.
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
A dict representing the item after replace went through.
- Raises
CosmosHttpResponseError – The replace failed or the item with given id does not exist.
- Return type
-
async
replace_throughput
(throughput: int, **kwargs: Any) → azure.cosmos.offer.Offer[source]¶ Replace the container’s throughput.
If no Offer already exists for the container, an exception is raised.
- Parameters
throughput – The throughput to be set (an integer).
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
Offer for the container, updated with new throughput.
- Raises
CosmosHttpResponseError – No offer exists for the container or the offer could not be updated.
- Return type
-
async
upsert_item
(body, pre_trigger_include=None, post_trigger_include=None, **kwargs) → Dict[str, Any][source]¶ Insert or update the specified item.
If the item already exists in the container, it is replaced. If the item does not already exist, it is inserted.
- Parameters
body – A dict-like object representing the item to update or insert.
pre_trigger_include – trigger id to be used as pre operation trigger.
post_trigger_include – trigger id to be used as post operation trigger.
- Keyword Arguments
session_token (str) – Token for use with Session consistency.
initial_headers (dict[str,str]) – Initial headers to be sent as part of the request.
etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.
match_condition (MatchConditions) – The match condition to use upon the etag.
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
A dict representing the upserted item.
- Raises
CosmosHttpResponseError – The given item could not be upserted.
- Return type
-
property
is_system_key
¶
-
property
scripts
¶
-
class
azure.cosmos.aio.
CosmosClient
(url: str, credential: Any, consistency_level: Optional[str] = None, **kwargs: Any)[source]¶ A client-side logical representation of an Azure Cosmos DB account.
Use this client to configure and execute requests to the Azure Cosmos DB service.
- Parameters
Example:
async with CosmosClient(url, key) as client:
Instantiate a new CosmosClient.
-
async
create_database
(id: str, offer_throughput: Optional[int] = None, **kwargs: Any) → azure.cosmos.aio.database.DatabaseProxy[source]¶ Create a new database with the given ID (name).
- Parameters
id – ID (name) of the database to create.
offer_throughput (int) – The provisioned throughput for this offer.
- Keyword Arguments
session_token (str) – Token for use with Session consistency.
initial_headers (dict[str,str]) – Initial headers to be sent as part of the request.
etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.
match_condition (MatchConditions) – The match condition to use upon the etag.
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
A DatabaseProxy instance representing the new database.
- Return type
- Raises
CosmosResourceExistsError – Database with the given ID already exists.
Example:
database_name = "testDatabase" try: database = await client.create_database(id=database_name) except exceptions.CosmosResourceExistsError: database = client.get_database_client(database=database_name)
-
async
create_database_if_not_exists
(id: str, offer_throughput: Optional[int] = None, **kwargs: Any) → azure.cosmos.aio.database.DatabaseProxy[source]¶ Create the database if it does not exist already.
If the database already exists, the existing settings are returned.
- ..note::
This function does not check or update existing database settings or offer throughput if they differ from what is passed in.
- Parameters
id – ID (name) of the database to read or create.
offer_throughput (int) – The provisioned throughput for this offer.
- Keyword Arguments
session_token (str) – Token for use with Session consistency.
initial_headers (dict[str,str]) – Initial headers to be sent as part of the request.
etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.
match_condition (MatchConditions) – The match condition to use upon the etag.
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
A DatabaseProxy instance representing the database.
- Return type
- Raises
CosmosHttpResponseError – The database read or creation failed.
-
async
delete_database
(database: Union[str, azure.cosmos.aio.database.DatabaseProxy, Dict[str, Any]], **kwargs: Any) → None[source]¶ Delete the database with the given ID (name).
- Parameters
database (str or dict(str, str) or DatabaseProxy) – The ID (name), dict representing the properties, or
DatabaseProxy
instance of the database to delete.- Keyword Arguments
session_token (str) – Token for use with Session consistency.
initial_headers (dict[str,str]) – Initial headers to be sent as part of the request.
etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.
match_condition (MatchConditions) – The match condition to use upon the etag.
response_hook (Callable) – A callable invoked with the response metadata.
- Raises
CosmosHttpResponseError – If the database couldn’t be deleted.
- Return type
-
classmethod
from_connection_string
(conn_str: str, credential: Optional[Union[str, Dict[str, str]]] = None, consistency_level: Optional[str] = None, **kwargs: Any) → azure.cosmos.aio.cosmos_client.CosmosClient[source]¶ Create a CosmosClient instance from a connection string.
This can be retrieved from the Azure portal.For full list of optional keyword arguments, see the CosmosClient constructor.
- Parameters
conn_str (str) – The connection string.
credential (str or Dict[str, str]) – Alternative credentials to use instead of the key provided in the connection string.
conn_str – The connection string.
consistency_level (Optional[str]) – Consistency level to use for the session. The default value is None (Account level).
-
get_database_client
(database: Union[str, azure.cosmos.aio.database.DatabaseProxy, Dict[str, Any]]) → azure.cosmos.aio.database.DatabaseProxy[source]¶ Retrieve an existing database with the ID (name) id.
- Parameters
database (str or dict(str, str) or DatabaseProxy) – The ID (name) representing the properties of the database to read.
- Returns
A DatabaseProxy instance representing the retrieved database.
- Return type
-
list_databases
(max_item_count: Optional[int] = None, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ List the databases in a Cosmos DB SQL database account.
- Parameters
max_item_count (int) – Max number of items to be returned in the enumeration operation.
- Keyword Arguments
- Returns
An AsyncItemPaged of database properties (dicts).
- Return type
-
query_databases
(query: str, parameters: Optional[List[Dict[str, Any]]] = None, max_item_count: Optional[int] = None, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ Query the databases in a Cosmos DB SQL database account.
- Parameters
query (str) – The Azure Cosmos DB SQL query to execute.
any]] parameters (list[dict[str,) – Optional array of parameters to the query. Each parameter is a dict() with ‘name’ and ‘value’ keys. Ignored if no query is provided.
max_item_count (int) – Max number of items to be returned in the enumeration operation.
- Keyword Arguments
- Returns
An AsyncItemPaged of database properties (dicts).
- Return type
-
class
azure.cosmos.aio.
DatabaseProxy
(client_connection: azure.cosmos.aio._cosmos_client_connection_async.CosmosClientConnection, id: str, properties: Optional[Dict[str, Any]] = None)[source]¶ An interface to interact with a specific database.
This class should not be instantiated directly. Instead use the
CosmosClient.get_database_client()
method.A database contains one or more containers, each of which can contain items, stored procedures, triggers, and user-defined functions.
A database can also have associated users, each of which is configured with a set of permissions for accessing certain containers, stored procedures, triggers, user-defined functions, or items.
- Variables
id – The ID (name) of the database.
An Azure Cosmos DB SQL API database has the following system-generated properties. These properties are read-only:
_rid: The resource ID.
_ts: When the resource was last updated. The value is a timestamp.
_self: The unique addressable URI for the resource.
_etag: The resource etag required for optimistic concurrency control.
_colls: The addressable path of the collections resource.
_users: The addressable path of the users resource.
- Parameters
client_connection (ClientSession) – Client from which this database was retrieved.
id (str) – ID (name) of the database.
-
async
create_container
(id: str, partition_key: Any, indexing_policy: Optional[Dict[str, Any]] = None, default_ttl: Optional[int] = None, offer_throughput: Optional[int] = None, unique_key_policy: Optional[Dict[str, Any]] = None, conflict_resolution_policy: Optional[Dict[str, Any]] = None, **kwargs: Any) → azure.cosmos.aio.container.ContainerProxy[source]¶ Create a new container with the given ID (name).
If a container with the given ID already exists, a CosmosResourceExistsError is raised.
- Parameters
id – ID (name) of container to create.
partition_key – The partition key to use for the container.
indexing_policy – The indexing policy to apply to the container.
default_ttl – Default time to live (TTL) for items in the container. If unspecified, items do not expire.
offer_throughput – The provisioned throughput for this offer.
unique_key_policy – The unique key policy to apply to the container.
conflict_resolution_policy – The conflict resolution policy to apply to the container.
- Keyword Arguments
session_token (str) – Token for use with Session consistency.
initial_headers (dict[str,str]) – Initial headers to be sent as part of the request.
etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.
match_condition (MatchConditions) – The match condition to use upon the etag.
response_hook (Callable) – A callable invoked with the response metadata.
analytical_storage_ttl – Analytical store time to live (TTL) for items in the container. A value of None leaves analytical storage off and a value of -1 turns analytical storage on with no TTL. Please note that analytical storage can only be enabled on Synapse Link enabled accounts.
- Returns
A ContainerProxy instance representing the new container.
- Raises
CosmosHttpResponseError – The container creation failed.
- Return type
Example:
container_name = "products" try: container = await database.create_container( id=container_name, partition_key=PartitionKey(path="/productName") ) except exceptions.CosmosResourceExistsError: container = database.get_container_client(container_name)
customer_container_name = "customers" try: customer_container = await database.create_container( id=customer_container_name, partition_key=PartitionKey(path="/city"), default_ttl=200, ) except exceptions.CosmosResourceExistsError: customer_container = database.get_container_client(customer_container_name)
-
async
create_container_if_not_exists
(id: str, partition_key: Any, indexing_policy: Optional[Dict[str, Any]] = None, default_ttl: Optional[int] = None, offer_throughput: Optional[int] = None, unique_key_policy: Optional[Dict[str, Any]] = None, conflict_resolution_policy: Optional[Dict[str, Any]] = None, **kwargs: Any) → azure.cosmos.aio.container.ContainerProxy[source]¶ Create a container if it does not exist already.
If the container already exists, the existing settings are returned. Note: it does not check or update the existing container settings or offer throughput if they differ from what was passed into the method.
- Parameters
id – ID (name) of container to read or create.
partition_key – The partition key to use for the container.
indexing_policy – The indexing policy to apply to the container.
default_ttl – Default time to live (TTL) for items in the container. If unspecified, items do not expire.
offer_throughput – The provisioned throughput for this offer.
unique_key_policy – The unique key policy to apply to the container.
conflict_resolution_policy – The conflict resolution policy to apply to the container.
- Keyword Arguments
session_token (str) – Token for use with Session consistency.
initial_headers (dict[str,str]) – Initial headers to be sent as part of the request.
etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.
match_condition (MatchConditions) – The match condition to use upon the etag.
response_hook (Callable) – A callable invoked with the response metadata.
analytical_storage_ttl – Analytical store time to live (TTL) for items in the container. A value of None leaves analytical storage off and a value of -1 turns analytical storage on with no TTL. Please note that analytical storage can only be enabled on Synapse Link enabled accounts.
- Returns
A ContainerProxy instance representing the container.
- Raises
CosmosHttpResponseError – The container read or creation failed.
- Return type
-
async
create_user
(body: Dict[str, Any], **kwargs: Any) → azure.cosmos.aio.user.UserProxy[source]¶ Create a new user in the container.
To update or replace an existing user, use the
ContainerProxy.upsert_user()
method.- Parameters
body – A dict-like object with an id key and value representing the user to be created. The user ID must be unique within the database, and consist of no more than 255 characters.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
A UserProxy instance representing the new user.
- Raises
CosmosHttpResponseError – If the given user couldn’t be created.
- Return type
Example:
try: await database.create_user(dict(id="Walter Harp")) print("Created user Walter Harp.") except exceptions.CosmosResourceExistsError: print("A user with that ID already exists.") except exceptions.CosmosHttpResponseError as failure: print("Failed to create user. Status code:{}".format(failure.status_code))
-
async
delete_container
(container: Union[str, azure.cosmos.aio.container.ContainerProxy, Dict[str, Any]], **kwargs: Any) → None[source]¶ Delete a container.
- Parameters
container – The ID (name) of the container to delete. You can either pass in the ID of the container to delete, a
ContainerProxy
instance or a dict representing the properties of the container.- Keyword Arguments
session_token (str) – Token for use with Session consistency.
initial_headers (dict[str,str]) – Initial headers to be sent as part of the request.
etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.
match_condition (MatchConditions) – The match condition to use upon the etag.
response_hook (Callable) – A callable invoked with the response metadata.
- Raises
CosmosHttpResponseError – If the container couldn’t be deleted.
- Return type
-
async
delete_user
(user: Union[str, azure.cosmos.aio.user.UserProxy, Dict[str, Any]], **kwargs: Any) → None[source]¶ Delete the specified user from the container.
- Parameters
user – The ID (name), dict representing the properties or
UserProxy
instance of the user to be deleted.- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Raises
CosmosHttpResponseError – The user wasn’t deleted successfully.
CosmosResourceNotFoundError – The user does not exist in the container.
- Return type
-
get_container_client
(container: Union[str, azure.cosmos.aio.container.ContainerProxy, Dict[str, Any]]) → azure.cosmos.aio.container.ContainerProxy[source]¶ Get a ContainerProxy for a container with specified ID (name).
- Parameters
container – The ID (name) of the container to be retrieved.
- Returns
A ContainerProxy instance representing the container.
- Return type
Example:
database = client.get_database_client(database_name) container = database.get_container_client(container_name)
-
get_user_client
(user_id: str) → azure.cosmos.aio.user.UserProxy[source]¶ Get a UserProxy for a user with specified ID.
- Parameters
user – The ID (name) of the user to be retrieved.
- Returns
A UserProxy instance representing the retrieved user.
- Return type
-
list_containers
(max_item_count: Optional[int] = None, **kwargs: Optional[bool]) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ List the containers in the database.
- Parameters
max_item_count – Max number of items to be returned in the enumeration operation.
- Keyword Arguments
- Returns
An AsyncItemPaged of container properties (dicts).
- Return type
Example:
database = client.get_database_client(database_name) async for container in database.list_containers(): print("Container ID: {}".format(container['id']))
-
list_users
(max_item_count: Optional[int] = None, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ List all the users in the container.
-
query_containers
(query: Optional[str] = None, parameters: Optional[List[Dict[str, Any]]] = None, max_item_count: Optional[int] = None, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ List the properties for containers in the current database.
- Parameters
query – The Azure Cosmos DB SQL query to execute.
parameters – Optional array of parameters to the query. Each parameter is a dict() with ‘name’ and ‘value’ keys. Ignored if no query is provided.
max_item_count – Max number of items to be returned in the enumeration operation.
- Keyword Arguments
- Returns
An AsyncItemPaged of container properties (dicts).
- Return type
-
query_users
(query: str, parameters: Optional[List[Dict[str, Any]]] = None, max_item_count: Optional[int] = None, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ Return all users matching the given query.
- Parameters
query – The Azure Cosmos DB SQL query to execute.
parameters – Optional array of parameters to the query. Each parameter is a dict() with ‘name’ and ‘value’ keys. Ignored if no query is provided.
max_item_count – Max number of users to be returned in the enumeration operation.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
An AsyncItemPaged of user properties (dicts).
- Return type
AsyncItemPaged[str, Any]
-
async
read
(**kwargs: Optional[bool]) → Dict[str, Any][source]¶ Read the database properties.
- Keyword Arguments
- Return type
Dict[Str, Any]
- Raises
CosmosHttpResponseError – If the given database couldn’t be retrieved.
-
async
read_offer
(**kwargs: Any) → azure.cosmos.offer.Offer[source]¶ Read the Offer object for this database.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
Offer for the database.
- Raises
CosmosHttpResponseError – If no offer exists for the database or if the offer could not be retrieved.
- Return type
-
async
replace_container
(container: Union[str, azure.cosmos.aio.container.ContainerProxy, Dict[str, Any]], partition_key: Any, indexing_policy: Optional[Dict[str, Any]] = None, default_ttl: Optional[int] = None, conflict_resolution_policy: Optional[Dict[str, Any]] = None, **kwargs: Any) → azure.cosmos.aio.container.ContainerProxy[source]¶ Reset the properties of the container.
Property changes are persisted immediately. Any properties not specified will be reset to their default values.
- Parameters
container – The ID (name), dict representing the properties or
ContainerProxy
instance of the container to be replaced.partition_key – The partition key to use for the container.
indexing_policy – The indexing policy to apply to the container.
default_ttl – Default time to live (TTL) for items in the container. If unspecified, items do not expire.
conflict_resolution_policy – The conflict resolution policy to apply to the container.
- Keyword Arguments
session_token (str) – Token for use with Session consistency.
etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.
match_condition (MatchConditions) – The match condition to use upon the etag.
initial_headers (dict[str,str]) – Initial headers to be sent as part of the request.
response_hook (Callable) – A callable invoked with the response metadata.
- Raises
CosmosHttpResponseError – Raised if the container couldn’t be replaced. This includes if the container with given id does not exist.
- Returns
A ContainerProxy instance representing the container after replace completed.
- Return type
Example:
# Set the TTL on the container to 3600 seconds (one hour) await database.replace_container(container, partition_key=PartitionKey(path='/productName'), default_ttl=3600) # Display the new TTL setting for the container container_props = await database.get_container_client(container_name).read() print("New container TTL: {}".format(json.dumps(container_props['defaultTtl'])))
-
async
replace_throughput
(throughput: Optional[int], **kwargs: Any) → azure.cosmos.offer.Offer[source]¶ Replace the database-level throughput.
- Parameters
throughput – The throughput to be set (an integer).
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
Offer for the database, updated with new throughput.
- Raises
CosmosHttpResponseError – If no offer exists for the database or if the offer could not be updated.
- Return type
-
async
replace_user
(user: Union[str, azure.cosmos.aio.user.UserProxy, Dict[str, Any]], body: Dict[str, Any], **kwargs: Any) → azure.cosmos.aio.user.UserProxy[source]¶ Replaces the specified user if it exists in the container.
- Parameters
user – The ID (name), dict representing the properties or
UserProxy
instance of the user to be replaced.body – A dict-like object representing the user to replace.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
A UserProxy instance representing the user after replace went through.
- Raises
CosmosHttpResponseError – If the replace failed or the user with given ID does not exist.
- Return type
-
async
upsert_user
(body: Dict[str, Any], **kwargs: Any) → azure.cosmos.aio.user.UserProxy[source]¶ Insert or update the specified user.
If the user already exists in the container, it is replaced. If the user does not already exist, it is inserted.
- Parameters
body – A dict-like object representing the user to update or insert.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
A UserProxy instance representing the upserted user.
- Raises
CosmosHttpResponseError – If the given user could not be upserted.
- Return type
-
class
azure.cosmos.aio.
ScriptsProxy
(container: ContainerProxy, client_connection: CosmosClientConnection, container_link: str)[source]¶ An interface to interact with stored procedures.
This class should not be instantiated directly. Instead, use the
ContainerProxy.scripts()
attribute.-
async
create_stored_procedure
(body: Dict[str, Any], **kwargs: Any) → Dict[str, Any][source]¶ Create a new stored procedure in the container.
To replace an existing sproc, use the
Container.scripts.replace_stored_procedure()
method.- Parameters
body – A dict-like object representing the sproc to create.
- Returns
A dict representing the new stored procedure.
- Raises
CosmosHttpResponseError – If the given stored procedure couldn’t be created.
- Return type
-
async
create_trigger
(body: Dict[str, Any], **kwargs: Any) → Dict[str, Any][source]¶ Create a trigger in the container.
To replace an existing trigger, use the
ContainerProxy.scripts.replace_trigger()
method.- Parameters
body – A dict-like object representing the trigger to create.
- Returns
A dict representing the new trigger.
- Raises
CosmosHttpResponseError – If the given trigger couldn’t be created.
- Return type
-
async
create_user_defined_function
(body: Dict[str, Any], **kwargs: Any) → Dict[str, Any][source]¶ Create a user-defined function in the container.
To replace an existing UDF, use the
ContainerProxy.scripts.replace_user_defined_function()
method.- Parameters
body – A dict-like object representing the udf to create.
- Returns
A dict representing the new user-defined function.
- Raises
CosmosHttpResponseError – If the user-defined function couldn’t be created.
- Return type
-
async
delete_stored_procedure
(sproc: Union[str, Dict[str, Any]], **kwargs: Any) → None[source]¶ Delete a specified stored procedure from the container.
If the stored procedure does not already exist in the container, an exception is raised.
- Parameters
sproc – The ID (name) or dict representing stored procedure to be deleted.
- Raises
CosmosHttpResponseError – The sproc wasn’t deleted successfully.
CosmosResourceNotFoundError – The sproc does not exist in the container.
- Return type
-
async
delete_trigger
(trigger: Union[str, Dict[str, Any]], **kwargs: Any) → None[source]¶ Delete a specified trigger from the container.
If the trigger does not already exist in the container, an exception is raised.
- Parameters
trigger – The ID (name) or dict representing trigger to be deleted.
- Raises
CosmosHttpResponseError – The trigger wasn’t deleted successfully.
CosmosResourceNotFoundError – The trigger does not exist in the container.
- Return type
-
async
delete_user_defined_function
(udf: Union[str, Dict[str, Any]], **kwargs: Any) → None[source]¶ Delete a specified user-defined function from the container.
If the UDF does not already exist in the container, an exception is raised.
- Parameters
udf – The ID (name) or dict representing udf to be deleted.
- Raises
CosmosHttpResponseError – The udf wasn’t deleted successfully.
CosmosResourceNotFoundError – The UDF does not exist in the container.
- Return type
-
async
execute_stored_procedure
(sproc: Union[str, Dict[str, Any]], partition_key: Optional[str] = None, params: Optional[List[Any]] = None, enable_script_logging: Optional[bool] = None, **kwargs: Any) → Any[source]¶ Execute a specified stored procedure.
If the stored procedure does not already exist in the container, an exception is raised.
- Parameters
sproc – The ID (name) or dict representing the stored procedure to be executed.
partition_key – Specifies the partition key to indicate which partition the sproc should execute on.
params – List of parameters to be passed to the stored procedure to be executed.
enable_script_logging (bool) – Enables or disables script logging for the current request.
- Returns
Result of the executed stored procedure for the given parameters.
- Raises
CosmosHttpResponseError – If the stored procedure execution failed or if the stored procedure with given id does not exists in the container.
- Return type
-
async
get_stored_procedure
(sproc: Union[str, Dict[str, Any]], **kwargs: Any) → Dict[str, Any][source]¶ Get the stored procedure identified by id.
- Parameters
sproc – The ID (name) or dict representing stored procedure to retrieve.
- Returns
A dict representing the retrieved stored procedure.
- Raises
CosmosHttpResponseError – If the given stored procedure couldn’t be retrieved.
- Return type
-
async
get_trigger
(trigger: Union[str, Dict[str, Any]], **kwargs: Any) → Dict[str, Any][source]¶ Get a trigger identified by id.
- Parameters
trigger – The ID (name) or dict representing trigger to retrieve.
- Returns
A dict representing the retrieved trigger.
- Raises
CosmosHttpResponseError – If the given trigger couldn’t be retrieved.
- Return type
-
async
get_user_defined_function
(udf: Union[str, Dict[str, Any]], **kwargs: Any) → Dict[str, Any][source]¶ Get a user-defined function identified by id.
- Parameters
udf – The ID (name) or dict representing udf to retrieve.
- Returns
A dict representing the retrieved user-defined function.
- Raises
CosmosHttpResponseError – If the user-defined function couldn’t be retrieved.
- Return type
-
list_stored_procedures
(max_item_count: Optional[int] = None, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ List all stored procedures in the container.
-
list_triggers
(max_item_count: Optional[int] = None, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ List all triggers in the container.
- Parameters
max_item_count – Max number of items to be returned in the enumeration operation.
- Returns
An AsyncItemPaged of triggers (dicts).
- Return type
AsyncItemPaged[Dict[str, Any]]
-
list_user_defined_functions
(max_item_count: Optional[int] = None, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ List all the user-defined functions in the container.
- Parameters
max_item_count – Max number of items to be returned in the enumeration operation.
- Returns
An AsyncItemPaged of user-defined functions (dicts).
- Return type
AsyncItemPaged[Dict[str, Any]]
-
query_stored_procedures
(query: str, parameters: Optional[List[str]] = None, max_item_count: Optional[int] = None, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ Return all stored procedures matching the given query.
- Parameters
query – The Azure Cosmos DB SQL query to execute.
parameters – Optional array of parameters to the query. Ignored if no query is provided.
max_item_count – Max number of items to be returned in the enumeration operation.
- Returns
An AsyncItemPaged of stored procedures (dicts).
- Return type
AsyncItemPaged[Dict[str, Any]]
-
query_triggers
(query: str, parameters: Optional[List[str]] = None, max_item_count: Optional[int] = None, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ Return all triggers matching the given query.
- Parameters
query – The Azure Cosmos DB SQL query to execute.
parameters – Optional array of parameters to the query. Ignored if no query is provided.
max_item_count – Max number of items to be returned in the enumeration operation.
- Returns
An AsyncItemPaged of triggers (dicts).
- Return type
AsyncItemPaged[Dict[str, Any]]
-
query_user_defined_functions
(query: str, parameters: Optional[List[str]] = None, max_item_count: Optional[int] = None, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ Return user-defined functions matching a given query.
- Parameters
query – The Azure Cosmos DB SQL query to execute.
parameters – Optional array of parameters to the query. Ignored if no query is provided.
max_item_count – Max number of items to be returned in the enumeration operation.
- Returns
An AsyncItemPaged of user-defined functions (dicts).
- Return type
AsyncItemPaged[Dict[str, Any]]
-
async
replace_stored_procedure
(sproc: Union[str, Dict[str, Any]], body: Dict[str, Any], **kwargs: Any) → Dict[str, Any][source]¶ Replace a specified stored procedure in the container.
If the stored procedure does not already exist in the container, an exception is raised.
- Parameters
sproc – The ID (name) or dict representing stored procedure to be replaced.
body – A dict-like object representing the sproc to replace.
- Returns
A dict representing the stored procedure after replace went through.
- Raises
CosmosHttpResponseError – If the replace failed or the stored procedure with given id does not exist.
- Return type
-
async
replace_trigger
(trigger: Union[str, Dict[str, Any]], body: Dict[str, Any], **kwargs: Any) → Dict[str, Any][source]¶ Replace a specified trigger in the container.
If the trigger does not already exist in the container, an exception is raised.
- Parameters
trigger – The ID (name) or dict representing trigger to be replaced.
body – A dict-like object representing the trigger to replace.
- Returns
A dict representing the trigger after replace went through.
- Raises
CosmosHttpResponseError – If the replace failed or the trigger with given id does not exist.
- Return type
-
async
replace_user_defined_function
(udf: Union[str, Dict[str, Any]], body: Dict[str, Any], **kwargs: Any) → Dict[str, Any][source]¶ Replace a specified user-defined function in the container.
If the UDF does not already exist in the container, an exception is raised.
- Parameters
udf – The ID (name) or dict representing udf to be replaced.
body – A dict-like object representing the udf to replace.
- Returns
A dict representing the user-defined function after replace went through.
- Raises
CosmosHttpResponseError – If the replace failed or the user-defined function with the given id does not exist.
- Return type
-
async
-
class
azure.cosmos.aio.
UserProxy
(client_connection: azure.cosmos.aio._cosmos_client_connection_async.CosmosClientConnection, id: str, database_link: str, properties: Optional[Dict[str, Any]] = None)[source]¶ An interface to interact with a specific user.
This class should not be instantiated directly. Instead, use the
DatabaseProxy.get_user_client()
method.-
async
create_permission
(body: Dict[str, Any], **kwargs: Any) → Permission[source]¶ Create a permission for the user.
To update or replace an existing permision, use the
UserProxy.upsert_permission()
method.- Parameters
body – A dict-like object representing the permission to create.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
A dict representing the new permission.
- Raises
CosmosHttpResponseError – If the given permission couldn’t be created.
- Return type
-
async
delete_permission
(permission: Union[str, Dict[str, Any], Permission], **kwargs: Any) → None[source]¶ Delete the specified permission from the user.
If the permission does not already exist, an exception is raised.
- Parameters
permission – The ID (name), dict representing the properties or
Permission
instance of the permission to be deleted.- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Raises
CosmosHttpResponseError – The permission wasn’t deleted successfully.
CosmosResourceNotFoundError – The permission does not exist for the user.
- Return type
-
async
get_permission
(permission: Union[str, Dict[str, Any], Permission], **kwargs: Any) → Permission[source]¶ Get the permission identified by id.
- Parameters
permission – The ID (name), dict representing the properties or
Permission
instance of the permission to be retrieved.- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
A dict representing the retrieved permission.
- Raises
CosmosHttpResponseError – If the given permission couldn’t be retrieved.
- Return type
-
list_permissions
(max_item_count: Optional[int] = None, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ List all permission for the user.
-
query_permissions
(query: str, parameters: Optional[List[str]] = None, max_item_count: Optional[int] = None, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ Return all permissions matching the given query.
- Parameters
query – The Azure Cosmos DB SQL query to execute.
parameters – Optional array of parameters to the query. Ignored if no query is provided.
max_item_count – Max number of permissions to be returned in the enumeration operation.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
An AsyncItemPaged of permissions (dicts).
- Return type
-
async
read
(**kwargs: Any) → Dict[str, Any][source]¶ Read user propertes.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
A dictionary of the retrieved user properties.
- Raises
CosmosHttpResponseError – If the given user couldn’t be retrieved.
- Return type
-
async
replace_permission
(permission: str, body: Union[str, Dict[str, Any], Permission], **kwargs: Any) → Permission[source]¶ Replaces the specified permission if it exists for the user.
If the permission does not already exist, an exception is raised.
- Parameters
permission – The ID (name), dict representing the properties or
Permission
instance of the permission to be replaced.body – A dict-like object representing the permission to replace.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
A dict representing the permission after replace went through.
- Raises
CosmosHttpResponseError – If the replace failed or the permission with given id does not exist.
- Return type
-
async
upsert_permission
(body: Dict[str, Any], **kwargs: Any) → Permission[source]¶ Insert or update the specified permission.
If the permission already exists in the container, it is replaced. If the permission does not exist, it is inserted.
- Parameters
body – A dict-like object representing the permission to update or insert.
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
A dict representing the upserted permission.
- Raises
CosmosHttpResponseError – If the given permission could not be upserted.
- Return type
-
async
Submodules¶
azure.cosmos.aio.container module¶
Create, read, update and delete items in the Azure Cosmos DB SQL API service.
-
class
azure.cosmos.aio.container.
ContainerProxy
(client_connection: azure.cosmos.aio._cosmos_client_connection_async.CosmosClientConnection, database_link: str, id: str, properties: Optional[Dict[str, Any]] = None)[source]¶ An interface to interact with a specific DB Container.
This class should not be instantiated directly. Instead, use the
get_container_client()
method to get an existing container, or theDatabaseProxy()
method to create a new container.A container in an Azure Cosmos DB SQL API database is a collection of documents, each of which is represented as an Item.
- Variables
-
async
create_item
(body, **kwargs) → Dict[str, Any][source]¶ Create an item in the container.
To update or replace an existing item, use the
ContainerProxy.upsert_item()
method.- Parameters
body – A dict-like object representing the item to create.
- Keyword Arguments
pre_trigger_include – trigger id to be used as pre operation trigger.
post_trigger_include – trigger id to be used as post operation trigger.
indexing_directive – Indicate whether the document should be omitted from indexing.
enable_automatic_id_generation (bool) – Enable automatic id generation if no id present.
session_token (str) – Token for use with Session consistency.
initial_headers (dict[str,str]) – Initial headers to be sent as part of the request.
etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.
match_condition (MatchConditions) – The match condition to use upon the etag.
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
A dict representing the new item.
- Raises
CosmosHttpResponseError – Item with the given ID already exists.
- Return type
-
async
delete_conflict
(conflict, partition_key, **kwargs) → None[source]¶ Delete a specified conflict from the container.
If the conflict does not already exist in the container, an exception is raised.
- Parameters
conflict – The ID (name) or dict representing the conflict to be deleted.
partition_key – Partition key for the conflict to delete.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Raises
CosmosHttpResponseError – The conflict wasn’t deleted successfully.
CosmosResourceNotFoundError – The conflict does not exist in the container.
- Return type
-
async
delete_item
(item, partition_key, pre_trigger_include=None, post_trigger_include=None, **kwargs) → None[source]¶ Delete the specified item from the container.
If the item does not already exist in the container, an exception is raised.
- Parameters
item – The ID (name) or dict representing item to be deleted.
partition_key – Specifies the partition key value for the item.
pre_trigger_include – trigger id to be used as pre operation trigger.
post_trigger_include – trigger id to be used as post operation trigger.
- Keyword Arguments
session_token (str) – Token for use with Session consistency.
initial_headers (dict[str,str]) – Initial headers to be sent as part of the request.
etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.
match_condition (MatchConditions) – The match condition to use upon the etag.
response_hook (Callable) – A callable invoked with the response metadata.
- Raises
CosmosHttpResponseError – The item wasn’t deleted successfully.
CosmosResourceNotFoundError – The item does not exist in the container.
- Return type
-
list_conflicts
(max_item_count: Optional[int] = None, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ List all the conflicts in the container.
- Parameters
max_item_count – Max number of items to be returned in the enumeration operation.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
An AsyncItemPaged of conflicts (dicts).
- Return type
AsyncItemPaged[Dict[str, Any]]
-
query_conflicts
(query, parameters=None, partition_key=None, max_item_count=None, **kwargs) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ Return all conflicts matching a given query.
- Parameters
query – The Azure Cosmos DB SQL query to execute.
parameters – Optional array of parameters to the query. Ignored if no query is provided.
partition_key – Specifies the partition key value for the item. If none is passed in, a cross partition query will be executed.
max_item_count – Max number of items to be returned in the enumeration operation.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
An AsyncItemPaged of conflicts (dicts).
- Return type
AsyncItemPaged[Dict[str, Any]]
-
query_items
(query, parameters=None, partition_key=None, max_item_count=None, enable_scan_in_query=None, populate_query_metrics=None, **kwargs) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ Return all results matching the given query.
You can use any value for the container name in the FROM clause, but often the container name is used. In the examples below, the container name is “products,” and is aliased as “p” for easier referencing in the WHERE clause.
- Parameters
query – The Azure Cosmos DB SQL query to execute.
parameters – Optional array of parameters to the query. Each parameter is a dict() with ‘name’ and ‘value’ keys. Ignored if no query is provided.
partition_key – Specifies the partition key value for the item. If none is provided, a cross-partition query will be executed
max_item_count – Max number of items to be returned in the enumeration operation.
enable_scan_in_query – Allow scan on the queries which couldn’t be served as indexing was opted out on the requested paths.
populate_query_metrics – Enable returning query metrics in response headers.
- Keyword Arguments
Provisional keyword argument max_integrated_cache_staleness_in_ms :keyword int max_integrated_cache_staleness_in_ms: The max cache staleness for the integrated cache in milliseconds.
For accounts configured to use the integrated cache, using Session or Eventual consistency, responses are guaranteed to be no staler than this value.
- Returns
An AsyncItemPaged of items (dicts).
- Return type
AsyncItemPaged[Dict[str, Any]]
Example:
import json async for item in container.query_items( query='SELECT * FROM products p WHERE p.productModel <> "DISCONTINUED"', enable_cross_partition_query=True, ): print(json.dumps(item, indent=True))
discontinued_items = container.query_items( query='SELECT * FROM products p WHERE p.productModel = @model AND p.productName="Widget"', parameters=[dict(name="@model", value="DISCONTINUED")], ) async for item in discontinued_items: print(json.dumps(item, indent=True))
-
query_items_change_feed
(partition_key_range_id=None, is_start_from_beginning=False, continuation=None, max_item_count=None, **kwargs) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ Get a sorted list of items that were changed, in the order in which they were modified.
- Parameters
partition_key_range_id – ChangeFeed requests can be executed against specific partition key ranges. This is used to process the change feed in parallel across multiple consumers.
partition_key – partition key at which ChangeFeed requests are targetted.
is_start_from_beginning – Get whether change feed should start from beginning (true) or from current (false). By default it’s start from current (false).
continuation – e_tag value to be used as continuation for reading change feed.
max_item_count – Max number of items to be returned in the enumeration operation.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
An AsyncItemPaged of items (dicts).
- Return type
AsyncItemPaged[Dict[str, Any]]
-
async
read
(populate_partition_key_range_statistics=None, populate_quota_info=None, **kwargs) → Dict[str, Any][source]¶ Read the container properties.
- Parameters
populate_partition_key_range_statistics – Enable returning partition key range statistics in response headers.
populate_quota_info – Enable returning collection storage quota information in response headers.
- Keyword Arguments
- Raises
CosmosHttpResponseError – Raised if the container couldn’t be retrieved. This includes if the container does not exist.
- Returns
Dict representing the retrieved container.
- Return type
-
read_all_items
(max_item_count=None, **kwargs) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ List all the items in the container.
- Parameters
max_item_count – Max number of items to be returned in the enumeration operation.
- Keyword Arguments
Provisional keyword argument max_integrated_cache_staleness_in_ms :keyword int max_integrated_cache_staleness_in_ms: The max cache staleness for the integrated cache in milliseconds.
For accounts configured to use the integrated cache, using Session or Eventual consistency, responses are guaranteed to be no staler than this value.
- Returns
An AsyncItemPaged of items (dicts).
- Return type
AsyncItemPaged[Dict[str, Any]]
-
async
read_conflict
(conflict, partition_key, **kwargs) → Dict[str, Any][source]¶ Get the conflict identified by conflict.
- Parameters
conflict – The ID (name) or dict representing the conflict to retrieve.
partition_key – Partition key for the conflict to retrieve.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
A dict representing the retrieved conflict.
- Raises
CosmosHttpResponseError – The given conflict couldn’t be retrieved.
- Return type
-
async
read_item
(item, partition_key, **kwargs) → Dict[str, Any][source]¶ Get the item identified by item.
- Parameters
item – The ID (name) or dict representing item to retrieve.
partition_key – Partition key for the item to retrieve.
- Keyword Arguments
Provisional keyword argument max_integrated_cache_staleness_in_ms :keyword int max_integrated_cache_staleness_in_ms: The max cache staleness for the integrated cache in milliseconds.
For accounts configured to use the integrated cache, using Session or Eventual consistency, responses are guaranteed to be no staler than this value.
- Returns
Dict representing the item to be retrieved.
- Raises
CosmosHttpResponseError – The given item couldn’t be retrieved.
- Return type
Example:
item = await container.read_item("item2", partition_key="Widget") item["productModel"] = "DISCONTINUED" updated_item = await container.upsert_item(item)
-
async
read_offer
(**kwargs: Any) → azure.cosmos.offer.Offer[source]¶ Read the Offer object for this container.
If no Offer already exists for the container, an exception is raised.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
Offer for the container.
- Raises
CosmosHttpResponseError – No offer exists for the container or the offer could not be retrieved.
- Return type
-
async
replace_item
(item, body, pre_trigger_include=None, post_trigger_include=None, **kwargs) → Dict[str, Any][source]¶ Replaces the specified item if it exists in the container.
If the item does not already exist in the container, an exception is raised.
- Parameters
item – The ID (name) or dict representing item to be replaced.
body – A dict-like object representing the item to replace.
pre_trigger_include – trigger id to be used as pre operation trigger.
post_trigger_include – trigger id to be used as post operation trigger.
- Keyword Arguments
session_token (str) – Token for use with Session consistency.
initial_headers (dict[str,str]) – Initial headers to be sent as part of the request.
etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.
match_condition (MatchConditions) – The match condition to use upon the etag.
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
A dict representing the item after replace went through.
- Raises
CosmosHttpResponseError – The replace failed or the item with given id does not exist.
- Return type
-
async
replace_throughput
(throughput: int, **kwargs: Any) → azure.cosmos.offer.Offer[source]¶ Replace the container’s throughput.
If no Offer already exists for the container, an exception is raised.
- Parameters
throughput – The throughput to be set (an integer).
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
Offer for the container, updated with new throughput.
- Raises
CosmosHttpResponseError – No offer exists for the container or the offer could not be updated.
- Return type
-
async
upsert_item
(body, pre_trigger_include=None, post_trigger_include=None, **kwargs) → Dict[str, Any][source]¶ Insert or update the specified item.
If the item already exists in the container, it is replaced. If the item does not already exist, it is inserted.
- Parameters
body – A dict-like object representing the item to update or insert.
pre_trigger_include – trigger id to be used as pre operation trigger.
post_trigger_include – trigger id to be used as post operation trigger.
- Keyword Arguments
session_token (str) – Token for use with Session consistency.
initial_headers (dict[str,str]) – Initial headers to be sent as part of the request.
etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.
match_condition (MatchConditions) – The match condition to use upon the etag.
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
A dict representing the upserted item.
- Raises
CosmosHttpResponseError – The given item could not be upserted.
- Return type
-
property
is_system_key
¶
-
property
scripts
¶
azure.cosmos.aio.cosmos_client module¶
Create, read, and delete databases in the Azure Cosmos DB SQL API service.
-
class
azure.cosmos.aio.cosmos_client.
CosmosClient
(url: str, credential: Any, consistency_level: Optional[str] = None, **kwargs: Any)[source]¶ A client-side logical representation of an Azure Cosmos DB account.
Use this client to configure and execute requests to the Azure Cosmos DB service.
- Parameters
Example:
async with CosmosClient(url, key) as client:
Instantiate a new CosmosClient.
-
async
create_database
(id: str, offer_throughput: Optional[int] = None, **kwargs: Any) → azure.cosmos.aio.database.DatabaseProxy[source]¶ Create a new database with the given ID (name).
- Parameters
id – ID (name) of the database to create.
offer_throughput (int) – The provisioned throughput for this offer.
- Keyword Arguments
session_token (str) – Token for use with Session consistency.
initial_headers (dict[str,str]) – Initial headers to be sent as part of the request.
etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.
match_condition (MatchConditions) – The match condition to use upon the etag.
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
A DatabaseProxy instance representing the new database.
- Return type
- Raises
CosmosResourceExistsError – Database with the given ID already exists.
Example:
database_name = "testDatabase" try: database = await client.create_database(id=database_name) except exceptions.CosmosResourceExistsError: database = client.get_database_client(database=database_name)
-
async
create_database_if_not_exists
(id: str, offer_throughput: Optional[int] = None, **kwargs: Any) → azure.cosmos.aio.database.DatabaseProxy[source]¶ Create the database if it does not exist already.
If the database already exists, the existing settings are returned.
- ..note::
This function does not check or update existing database settings or offer throughput if they differ from what is passed in.
- Parameters
id – ID (name) of the database to read or create.
offer_throughput (int) – The provisioned throughput for this offer.
- Keyword Arguments
session_token (str) – Token for use with Session consistency.
initial_headers (dict[str,str]) – Initial headers to be sent as part of the request.
etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.
match_condition (MatchConditions) – The match condition to use upon the etag.
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
A DatabaseProxy instance representing the database.
- Return type
- Raises
CosmosHttpResponseError – The database read or creation failed.
-
async
delete_database
(database: Union[str, azure.cosmos.aio.database.DatabaseProxy, Dict[str, Any]], **kwargs: Any) → None[source]¶ Delete the database with the given ID (name).
- Parameters
database (str or dict(str, str) or DatabaseProxy) – The ID (name), dict representing the properties, or
DatabaseProxy
instance of the database to delete.- Keyword Arguments
session_token (str) – Token for use with Session consistency.
initial_headers (dict[str,str]) – Initial headers to be sent as part of the request.
etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.
match_condition (MatchConditions) – The match condition to use upon the etag.
response_hook (Callable) – A callable invoked with the response metadata.
- Raises
CosmosHttpResponseError – If the database couldn’t be deleted.
- Return type
-
classmethod
from_connection_string
(conn_str: str, credential: Optional[Union[str, Dict[str, str]]] = None, consistency_level: Optional[str] = None, **kwargs: Any) → azure.cosmos.aio.cosmos_client.CosmosClient[source]¶ Create a CosmosClient instance from a connection string.
This can be retrieved from the Azure portal.For full list of optional keyword arguments, see the CosmosClient constructor.
- Parameters
conn_str (str) – The connection string.
credential (str or Dict[str, str]) – Alternative credentials to use instead of the key provided in the connection string.
conn_str – The connection string.
consistency_level (Optional[str]) – Consistency level to use for the session. The default value is None (Account level).
-
get_database_client
(database: Union[str, azure.cosmos.aio.database.DatabaseProxy, Dict[str, Any]]) → azure.cosmos.aio.database.DatabaseProxy[source]¶ Retrieve an existing database with the ID (name) id.
- Parameters
database (str or dict(str, str) or DatabaseProxy) – The ID (name) representing the properties of the database to read.
- Returns
A DatabaseProxy instance representing the retrieved database.
- Return type
-
list_databases
(max_item_count: Optional[int] = None, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ List the databases in a Cosmos DB SQL database account.
- Parameters
max_item_count (int) – Max number of items to be returned in the enumeration operation.
- Keyword Arguments
- Returns
An AsyncItemPaged of database properties (dicts).
- Return type
-
query_databases
(query: str, parameters: Optional[List[Dict[str, Any]]] = None, max_item_count: Optional[int] = None, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ Query the databases in a Cosmos DB SQL database account.
- Parameters
query (str) – The Azure Cosmos DB SQL query to execute.
any]] parameters (list[dict[str,) – Optional array of parameters to the query. Each parameter is a dict() with ‘name’ and ‘value’ keys. Ignored if no query is provided.
max_item_count (int) – Max number of items to be returned in the enumeration operation.
- Keyword Arguments
- Returns
An AsyncItemPaged of database properties (dicts).
- Return type
azure.cosmos.aio.database module¶
Interact with databases in the Azure Cosmos DB SQL API service.
-
class
azure.cosmos.aio.database.
DatabaseProxy
(client_connection: azure.cosmos.aio._cosmos_client_connection_async.CosmosClientConnection, id: str, properties: Optional[Dict[str, Any]] = None)[source]¶ An interface to interact with a specific database.
This class should not be instantiated directly. Instead use the
CosmosClient.get_database_client()
method.A database contains one or more containers, each of which can contain items, stored procedures, triggers, and user-defined functions.
A database can also have associated users, each of which is configured with a set of permissions for accessing certain containers, stored procedures, triggers, user-defined functions, or items.
- Variables
id – The ID (name) of the database.
An Azure Cosmos DB SQL API database has the following system-generated properties. These properties are read-only:
_rid: The resource ID.
_ts: When the resource was last updated. The value is a timestamp.
_self: The unique addressable URI for the resource.
_etag: The resource etag required for optimistic concurrency control.
_colls: The addressable path of the collections resource.
_users: The addressable path of the users resource.
- Parameters
client_connection (ClientSession) – Client from which this database was retrieved.
id (str) – ID (name) of the database.
-
async
create_container
(id: str, partition_key: Any, indexing_policy: Optional[Dict[str, Any]] = None, default_ttl: Optional[int] = None, offer_throughput: Optional[int] = None, unique_key_policy: Optional[Dict[str, Any]] = None, conflict_resolution_policy: Optional[Dict[str, Any]] = None, **kwargs: Any) → azure.cosmos.aio.container.ContainerProxy[source]¶ Create a new container with the given ID (name).
If a container with the given ID already exists, a CosmosResourceExistsError is raised.
- Parameters
id – ID (name) of container to create.
partition_key – The partition key to use for the container.
indexing_policy – The indexing policy to apply to the container.
default_ttl – Default time to live (TTL) for items in the container. If unspecified, items do not expire.
offer_throughput – The provisioned throughput for this offer.
unique_key_policy – The unique key policy to apply to the container.
conflict_resolution_policy – The conflict resolution policy to apply to the container.
- Keyword Arguments
session_token (str) – Token for use with Session consistency.
initial_headers (dict[str,str]) – Initial headers to be sent as part of the request.
etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.
match_condition (MatchConditions) – The match condition to use upon the etag.
response_hook (Callable) – A callable invoked with the response metadata.
analytical_storage_ttl – Analytical store time to live (TTL) for items in the container. A value of None leaves analytical storage off and a value of -1 turns analytical storage on with no TTL. Please note that analytical storage can only be enabled on Synapse Link enabled accounts.
- Returns
A ContainerProxy instance representing the new container.
- Raises
CosmosHttpResponseError – The container creation failed.
- Return type
Example:
container_name = "products" try: container = await database.create_container( id=container_name, partition_key=PartitionKey(path="/productName") ) except exceptions.CosmosResourceExistsError: container = database.get_container_client(container_name)
customer_container_name = "customers" try: customer_container = await database.create_container( id=customer_container_name, partition_key=PartitionKey(path="/city"), default_ttl=200, ) except exceptions.CosmosResourceExistsError: customer_container = database.get_container_client(customer_container_name)
-
async
create_container_if_not_exists
(id: str, partition_key: Any, indexing_policy: Optional[Dict[str, Any]] = None, default_ttl: Optional[int] = None, offer_throughput: Optional[int] = None, unique_key_policy: Optional[Dict[str, Any]] = None, conflict_resolution_policy: Optional[Dict[str, Any]] = None, **kwargs: Any) → azure.cosmos.aio.container.ContainerProxy[source]¶ Create a container if it does not exist already.
If the container already exists, the existing settings are returned. Note: it does not check or update the existing container settings or offer throughput if they differ from what was passed into the method.
- Parameters
id – ID (name) of container to read or create.
partition_key – The partition key to use for the container.
indexing_policy – The indexing policy to apply to the container.
default_ttl – Default time to live (TTL) for items in the container. If unspecified, items do not expire.
offer_throughput – The provisioned throughput for this offer.
unique_key_policy – The unique key policy to apply to the container.
conflict_resolution_policy – The conflict resolution policy to apply to the container.
- Keyword Arguments
session_token (str) – Token for use with Session consistency.
initial_headers (dict[str,str]) – Initial headers to be sent as part of the request.
etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.
match_condition (MatchConditions) – The match condition to use upon the etag.
response_hook (Callable) – A callable invoked with the response metadata.
analytical_storage_ttl – Analytical store time to live (TTL) for items in the container. A value of None leaves analytical storage off and a value of -1 turns analytical storage on with no TTL. Please note that analytical storage can only be enabled on Synapse Link enabled accounts.
- Returns
A ContainerProxy instance representing the container.
- Raises
CosmosHttpResponseError – The container read or creation failed.
- Return type
-
async
create_user
(body: Dict[str, Any], **kwargs: Any) → azure.cosmos.aio.user.UserProxy[source]¶ Create a new user in the container.
To update or replace an existing user, use the
ContainerProxy.upsert_user()
method.- Parameters
body – A dict-like object with an id key and value representing the user to be created. The user ID must be unique within the database, and consist of no more than 255 characters.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
A UserProxy instance representing the new user.
- Raises
CosmosHttpResponseError – If the given user couldn’t be created.
- Return type
Example:
try: await database.create_user(dict(id="Walter Harp")) print("Created user Walter Harp.") except exceptions.CosmosResourceExistsError: print("A user with that ID already exists.") except exceptions.CosmosHttpResponseError as failure: print("Failed to create user. Status code:{}".format(failure.status_code))
-
async
delete_container
(container: Union[str, azure.cosmos.aio.container.ContainerProxy, Dict[str, Any]], **kwargs: Any) → None[source]¶ Delete a container.
- Parameters
container – The ID (name) of the container to delete. You can either pass in the ID of the container to delete, a
ContainerProxy
instance or a dict representing the properties of the container.- Keyword Arguments
session_token (str) – Token for use with Session consistency.
initial_headers (dict[str,str]) – Initial headers to be sent as part of the request.
etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.
match_condition (MatchConditions) – The match condition to use upon the etag.
response_hook (Callable) – A callable invoked with the response metadata.
- Raises
CosmosHttpResponseError – If the container couldn’t be deleted.
- Return type
-
async
delete_user
(user: Union[str, azure.cosmos.aio.user.UserProxy, Dict[str, Any]], **kwargs: Any) → None[source]¶ Delete the specified user from the container.
- Parameters
user – The ID (name), dict representing the properties or
UserProxy
instance of the user to be deleted.- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Raises
CosmosHttpResponseError – The user wasn’t deleted successfully.
CosmosResourceNotFoundError – The user does not exist in the container.
- Return type
-
get_container_client
(container: Union[str, azure.cosmos.aio.container.ContainerProxy, Dict[str, Any]]) → azure.cosmos.aio.container.ContainerProxy[source]¶ Get a ContainerProxy for a container with specified ID (name).
- Parameters
container – The ID (name) of the container to be retrieved.
- Returns
A ContainerProxy instance representing the container.
- Return type
Example:
database = client.get_database_client(database_name) container = database.get_container_client(container_name)
-
get_user_client
(user_id: str) → azure.cosmos.aio.user.UserProxy[source]¶ Get a UserProxy for a user with specified ID.
- Parameters
user – The ID (name) of the user to be retrieved.
- Returns
A UserProxy instance representing the retrieved user.
- Return type
-
list_containers
(max_item_count: Optional[int] = None, **kwargs: Optional[bool]) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ List the containers in the database.
- Parameters
max_item_count – Max number of items to be returned in the enumeration operation.
- Keyword Arguments
- Returns
An AsyncItemPaged of container properties (dicts).
- Return type
Example:
database = client.get_database_client(database_name) async for container in database.list_containers(): print("Container ID: {}".format(container['id']))
-
list_users
(max_item_count: Optional[int] = None, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ List all the users in the container.
-
query_containers
(query: Optional[str] = None, parameters: Optional[List[Dict[str, Any]]] = None, max_item_count: Optional[int] = None, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ List the properties for containers in the current database.
- Parameters
query – The Azure Cosmos DB SQL query to execute.
parameters – Optional array of parameters to the query. Each parameter is a dict() with ‘name’ and ‘value’ keys. Ignored if no query is provided.
max_item_count – Max number of items to be returned in the enumeration operation.
- Keyword Arguments
- Returns
An AsyncItemPaged of container properties (dicts).
- Return type
-
query_users
(query: str, parameters: Optional[List[Dict[str, Any]]] = None, max_item_count: Optional[int] = None, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ Return all users matching the given query.
- Parameters
query – The Azure Cosmos DB SQL query to execute.
parameters – Optional array of parameters to the query. Each parameter is a dict() with ‘name’ and ‘value’ keys. Ignored if no query is provided.
max_item_count – Max number of users to be returned in the enumeration operation.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
An AsyncItemPaged of user properties (dicts).
- Return type
AsyncItemPaged[str, Any]
-
async
read
(**kwargs: Optional[bool]) → Dict[str, Any][source]¶ Read the database properties.
- Keyword Arguments
- Return type
Dict[Str, Any]
- Raises
CosmosHttpResponseError – If the given database couldn’t be retrieved.
-
async
read_offer
(**kwargs: Any) → azure.cosmos.offer.Offer[source]¶ Read the Offer object for this database.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
Offer for the database.
- Raises
CosmosHttpResponseError – If no offer exists for the database or if the offer could not be retrieved.
- Return type
-
async
replace_container
(container: Union[str, azure.cosmos.aio.container.ContainerProxy, Dict[str, Any]], partition_key: Any, indexing_policy: Optional[Dict[str, Any]] = None, default_ttl: Optional[int] = None, conflict_resolution_policy: Optional[Dict[str, Any]] = None, **kwargs: Any) → azure.cosmos.aio.container.ContainerProxy[source]¶ Reset the properties of the container.
Property changes are persisted immediately. Any properties not specified will be reset to their default values.
- Parameters
container – The ID (name), dict representing the properties or
ContainerProxy
instance of the container to be replaced.partition_key – The partition key to use for the container.
indexing_policy – The indexing policy to apply to the container.
default_ttl – Default time to live (TTL) for items in the container. If unspecified, items do not expire.
conflict_resolution_policy – The conflict resolution policy to apply to the container.
- Keyword Arguments
session_token (str) – Token for use with Session consistency.
etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.
match_condition (MatchConditions) – The match condition to use upon the etag.
initial_headers (dict[str,str]) – Initial headers to be sent as part of the request.
response_hook (Callable) – A callable invoked with the response metadata.
- Raises
CosmosHttpResponseError – Raised if the container couldn’t be replaced. This includes if the container with given id does not exist.
- Returns
A ContainerProxy instance representing the container after replace completed.
- Return type
Example:
# Set the TTL on the container to 3600 seconds (one hour) await database.replace_container(container, partition_key=PartitionKey(path='/productName'), default_ttl=3600) # Display the new TTL setting for the container container_props = await database.get_container_client(container_name).read() print("New container TTL: {}".format(json.dumps(container_props['defaultTtl'])))
-
async
replace_throughput
(throughput: Optional[int], **kwargs: Any) → azure.cosmos.offer.Offer[source]¶ Replace the database-level throughput.
- Parameters
throughput – The throughput to be set (an integer).
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
Offer for the database, updated with new throughput.
- Raises
CosmosHttpResponseError – If no offer exists for the database or if the offer could not be updated.
- Return type
-
async
replace_user
(user: Union[str, azure.cosmos.aio.user.UserProxy, Dict[str, Any]], body: Dict[str, Any], **kwargs: Any) → azure.cosmos.aio.user.UserProxy[source]¶ Replaces the specified user if it exists in the container.
- Parameters
user – The ID (name), dict representing the properties or
UserProxy
instance of the user to be replaced.body – A dict-like object representing the user to replace.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
A UserProxy instance representing the user after replace went through.
- Raises
CosmosHttpResponseError – If the replace failed or the user with given ID does not exist.
- Return type
-
async
upsert_user
(body: Dict[str, Any], **kwargs: Any) → azure.cosmos.aio.user.UserProxy[source]¶ Insert or update the specified user.
If the user already exists in the container, it is replaced. If the user does not already exist, it is inserted.
- Parameters
body – A dict-like object representing the user to update or insert.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
A UserProxy instance representing the upserted user.
- Raises
CosmosHttpResponseError – If the given user could not be upserted.
- Return type
azure.cosmos.aio.scripts module¶
Create, read, update and delete and execute scripts in the Azure Cosmos DB SQL API service.
-
class
azure.cosmos.aio.scripts.
ScriptType
[source]¶ -
StoredProcedure
= 'sprocs'¶
-
Trigger
= 'triggers'¶
-
UserDefinedFunction
= 'udfs'¶
-
-
class
azure.cosmos.aio.scripts.
ScriptsProxy
(container: ContainerProxy, client_connection: CosmosClientConnection, container_link: str)[source]¶ An interface to interact with stored procedures.
This class should not be instantiated directly. Instead, use the
ContainerProxy.scripts()
attribute.-
async
create_stored_procedure
(body: Dict[str, Any], **kwargs: Any) → Dict[str, Any][source]¶ Create a new stored procedure in the container.
To replace an existing sproc, use the
Container.scripts.replace_stored_procedure()
method.- Parameters
body – A dict-like object representing the sproc to create.
- Returns
A dict representing the new stored procedure.
- Raises
CosmosHttpResponseError – If the given stored procedure couldn’t be created.
- Return type
-
async
create_trigger
(body: Dict[str, Any], **kwargs: Any) → Dict[str, Any][source]¶ Create a trigger in the container.
To replace an existing trigger, use the
ContainerProxy.scripts.replace_trigger()
method.- Parameters
body – A dict-like object representing the trigger to create.
- Returns
A dict representing the new trigger.
- Raises
CosmosHttpResponseError – If the given trigger couldn’t be created.
- Return type
-
async
create_user_defined_function
(body: Dict[str, Any], **kwargs: Any) → Dict[str, Any][source]¶ Create a user-defined function in the container.
To replace an existing UDF, use the
ContainerProxy.scripts.replace_user_defined_function()
method.- Parameters
body – A dict-like object representing the udf to create.
- Returns
A dict representing the new user-defined function.
- Raises
CosmosHttpResponseError – If the user-defined function couldn’t be created.
- Return type
-
async
delete_stored_procedure
(sproc: Union[str, Dict[str, Any]], **kwargs: Any) → None[source]¶ Delete a specified stored procedure from the container.
If the stored procedure does not already exist in the container, an exception is raised.
- Parameters
sproc – The ID (name) or dict representing stored procedure to be deleted.
- Raises
CosmosHttpResponseError – The sproc wasn’t deleted successfully.
CosmosResourceNotFoundError – The sproc does not exist in the container.
- Return type
-
async
delete_trigger
(trigger: Union[str, Dict[str, Any]], **kwargs: Any) → None[source]¶ Delete a specified trigger from the container.
If the trigger does not already exist in the container, an exception is raised.
- Parameters
trigger – The ID (name) or dict representing trigger to be deleted.
- Raises
CosmosHttpResponseError – The trigger wasn’t deleted successfully.
CosmosResourceNotFoundError – The trigger does not exist in the container.
- Return type
-
async
delete_user_defined_function
(udf: Union[str, Dict[str, Any]], **kwargs: Any) → None[source]¶ Delete a specified user-defined function from the container.
If the UDF does not already exist in the container, an exception is raised.
- Parameters
udf – The ID (name) or dict representing udf to be deleted.
- Raises
CosmosHttpResponseError – The udf wasn’t deleted successfully.
CosmosResourceNotFoundError – The UDF does not exist in the container.
- Return type
-
async
execute_stored_procedure
(sproc: Union[str, Dict[str, Any]], partition_key: Optional[str] = None, params: Optional[List[Any]] = None, enable_script_logging: Optional[bool] = None, **kwargs: Any) → Any[source]¶ Execute a specified stored procedure.
If the stored procedure does not already exist in the container, an exception is raised.
- Parameters
sproc – The ID (name) or dict representing the stored procedure to be executed.
partition_key – Specifies the partition key to indicate which partition the sproc should execute on.
params – List of parameters to be passed to the stored procedure to be executed.
enable_script_logging (bool) – Enables or disables script logging for the current request.
- Returns
Result of the executed stored procedure for the given parameters.
- Raises
CosmosHttpResponseError – If the stored procedure execution failed or if the stored procedure with given id does not exists in the container.
- Return type
-
async
get_stored_procedure
(sproc: Union[str, Dict[str, Any]], **kwargs: Any) → Dict[str, Any][source]¶ Get the stored procedure identified by id.
- Parameters
sproc – The ID (name) or dict representing stored procedure to retrieve.
- Returns
A dict representing the retrieved stored procedure.
- Raises
CosmosHttpResponseError – If the given stored procedure couldn’t be retrieved.
- Return type
-
async
get_trigger
(trigger: Union[str, Dict[str, Any]], **kwargs: Any) → Dict[str, Any][source]¶ Get a trigger identified by id.
- Parameters
trigger – The ID (name) or dict representing trigger to retrieve.
- Returns
A dict representing the retrieved trigger.
- Raises
CosmosHttpResponseError – If the given trigger couldn’t be retrieved.
- Return type
-
async
get_user_defined_function
(udf: Union[str, Dict[str, Any]], **kwargs: Any) → Dict[str, Any][source]¶ Get a user-defined function identified by id.
- Parameters
udf – The ID (name) or dict representing udf to retrieve.
- Returns
A dict representing the retrieved user-defined function.
- Raises
CosmosHttpResponseError – If the user-defined function couldn’t be retrieved.
- Return type
-
list_stored_procedures
(max_item_count: Optional[int] = None, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ List all stored procedures in the container.
-
list_triggers
(max_item_count: Optional[int] = None, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ List all triggers in the container.
- Parameters
max_item_count – Max number of items to be returned in the enumeration operation.
- Returns
An AsyncItemPaged of triggers (dicts).
- Return type
AsyncItemPaged[Dict[str, Any]]
-
list_user_defined_functions
(max_item_count: Optional[int] = None, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ List all the user-defined functions in the container.
- Parameters
max_item_count – Max number of items to be returned in the enumeration operation.
- Returns
An AsyncItemPaged of user-defined functions (dicts).
- Return type
AsyncItemPaged[Dict[str, Any]]
-
query_stored_procedures
(query: str, parameters: Optional[List[str]] = None, max_item_count: Optional[int] = None, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ Return all stored procedures matching the given query.
- Parameters
query – The Azure Cosmos DB SQL query to execute.
parameters – Optional array of parameters to the query. Ignored if no query is provided.
max_item_count – Max number of items to be returned in the enumeration operation.
- Returns
An AsyncItemPaged of stored procedures (dicts).
- Return type
AsyncItemPaged[Dict[str, Any]]
-
query_triggers
(query: str, parameters: Optional[List[str]] = None, max_item_count: Optional[int] = None, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ Return all triggers matching the given query.
- Parameters
query – The Azure Cosmos DB SQL query to execute.
parameters – Optional array of parameters to the query. Ignored if no query is provided.
max_item_count – Max number of items to be returned in the enumeration operation.
- Returns
An AsyncItemPaged of triggers (dicts).
- Return type
AsyncItemPaged[Dict[str, Any]]
-
query_user_defined_functions
(query: str, parameters: Optional[List[str]] = None, max_item_count: Optional[int] = None, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ Return user-defined functions matching a given query.
- Parameters
query – The Azure Cosmos DB SQL query to execute.
parameters – Optional array of parameters to the query. Ignored if no query is provided.
max_item_count – Max number of items to be returned in the enumeration operation.
- Returns
An AsyncItemPaged of user-defined functions (dicts).
- Return type
AsyncItemPaged[Dict[str, Any]]
-
async
replace_stored_procedure
(sproc: Union[str, Dict[str, Any]], body: Dict[str, Any], **kwargs: Any) → Dict[str, Any][source]¶ Replace a specified stored procedure in the container.
If the stored procedure does not already exist in the container, an exception is raised.
- Parameters
sproc – The ID (name) or dict representing stored procedure to be replaced.
body – A dict-like object representing the sproc to replace.
- Returns
A dict representing the stored procedure after replace went through.
- Raises
CosmosHttpResponseError – If the replace failed or the stored procedure with given id does not exist.
- Return type
-
async
replace_trigger
(trigger: Union[str, Dict[str, Any]], body: Dict[str, Any], **kwargs: Any) → Dict[str, Any][source]¶ Replace a specified trigger in the container.
If the trigger does not already exist in the container, an exception is raised.
- Parameters
trigger – The ID (name) or dict representing trigger to be replaced.
body – A dict-like object representing the trigger to replace.
- Returns
A dict representing the trigger after replace went through.
- Raises
CosmosHttpResponseError – If the replace failed or the trigger with given id does not exist.
- Return type
-
async
replace_user_defined_function
(udf: Union[str, Dict[str, Any]], body: Dict[str, Any], **kwargs: Any) → Dict[str, Any][source]¶ Replace a specified user-defined function in the container.
If the UDF does not already exist in the container, an exception is raised.
- Parameters
udf – The ID (name) or dict representing udf to be replaced.
body – A dict-like object representing the udf to replace.
- Returns
A dict representing the user-defined function after replace went through.
- Raises
CosmosHttpResponseError – If the replace failed or the user-defined function with the given id does not exist.
- Return type
-
async
azure.cosmos.aio.user module¶
Create, read, update and delete users in the Azure Cosmos DB SQL API service.
-
class
azure.cosmos.aio.user.
UserProxy
(client_connection: azure.cosmos.aio._cosmos_client_connection_async.CosmosClientConnection, id: str, database_link: str, properties: Optional[Dict[str, Any]] = None)[source]¶ An interface to interact with a specific user.
This class should not be instantiated directly. Instead, use the
DatabaseProxy.get_user_client()
method.-
async
create_permission
(body: Dict[str, Any], **kwargs: Any) → Permission[source]¶ Create a permission for the user.
To update or replace an existing permision, use the
UserProxy.upsert_permission()
method.- Parameters
body – A dict-like object representing the permission to create.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
A dict representing the new permission.
- Raises
CosmosHttpResponseError – If the given permission couldn’t be created.
- Return type
-
async
delete_permission
(permission: Union[str, Dict[str, Any], Permission], **kwargs: Any) → None[source]¶ Delete the specified permission from the user.
If the permission does not already exist, an exception is raised.
- Parameters
permission – The ID (name), dict representing the properties or
Permission
instance of the permission to be deleted.- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Raises
CosmosHttpResponseError – The permission wasn’t deleted successfully.
CosmosResourceNotFoundError – The permission does not exist for the user.
- Return type
-
async
get_permission
(permission: Union[str, Dict[str, Any], Permission], **kwargs: Any) → Permission[source]¶ Get the permission identified by id.
- Parameters
permission – The ID (name), dict representing the properties or
Permission
instance of the permission to be retrieved.- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
A dict representing the retrieved permission.
- Raises
CosmosHttpResponseError – If the given permission couldn’t be retrieved.
- Return type
-
list_permissions
(max_item_count: Optional[int] = None, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ List all permission for the user.
-
query_permissions
(query: str, parameters: Optional[List[str]] = None, max_item_count: Optional[int] = None, **kwargs: Any) → azure.core.async_paging.AsyncItemPaged[Dict[str, Any]][source]¶ Return all permissions matching the given query.
- Parameters
query – The Azure Cosmos DB SQL query to execute.
parameters – Optional array of parameters to the query. Ignored if no query is provided.
max_item_count – Max number of permissions to be returned in the enumeration operation.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
An AsyncItemPaged of permissions (dicts).
- Return type
-
async
read
(**kwargs: Any) → Dict[str, Any][source]¶ Read user propertes.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
A dictionary of the retrieved user properties.
- Raises
CosmosHttpResponseError – If the given user couldn’t be retrieved.
- Return type
-
async
replace_permission
(permission: str, body: Union[str, Dict[str, Any], Permission], **kwargs: Any) → Permission[source]¶ Replaces the specified permission if it exists for the user.
If the permission does not already exist, an exception is raised.
- Parameters
permission – The ID (name), dict representing the properties or
Permission
instance of the permission to be replaced.body – A dict-like object representing the permission to replace.
- Keyword Arguments
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
A dict representing the permission after replace went through.
- Raises
CosmosHttpResponseError – If the replace failed or the permission with given id does not exist.
- Return type
-
async
upsert_permission
(body: Dict[str, Any], **kwargs: Any) → Permission[source]¶ Insert or update the specified permission.
If the permission already exists in the container, it is replaced. If the permission does not exist, it is inserted.
- Parameters
body – A dict-like object representing the permission to update or insert.
response_hook (Callable) – A callable invoked with the response metadata.
- Returns
A dict representing the upserted permission.
- Raises
CosmosHttpResponseError – If the given permission could not be upserted.
- Return type
-
async