diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_auth_policy.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_auth_policy.py index 1210335e37e7..4741cbcc8afd 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_auth_policy.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_auth_policy.py @@ -105,8 +105,10 @@ def send(self, request): # type: (PipelineRequest) -> PipelineResponse """Authorize request with a bearer token and send it to the next policy - :param request: The pipeline request object + :param request: The pipeline request object. :type request: ~azure.core.pipeline.PipelineRequest + :returns: The pipeline response object. + :rtype: ~azure.core.pipeline.PipelineResponse """ self.on_request(request) try: @@ -138,9 +140,10 @@ def on_challenge(self, request, response): :param ~azure.core.pipeline.PipelineRequest request: the request which elicited an authentication challenge :param ~azure.core.pipeline.PipelineResponse response: the resource provider's response - :returns: a bool indicating whether the policy should send the request + :returns: a boolean indicating whether the policy should send the request + :rtype: bool """ - # pylint:disable=unused-argument,no-self-use + # pylint:disable=unused-argument return False def on_response(self, request, response): @@ -162,5 +165,5 @@ def on_exception(self, request): :param request: The Pipeline request object :type request: ~azure.core.pipeline.PipelineRequest """ - # pylint: disable=no-self-use,unused-argument + # pylint: disable=unused-argument return diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_base.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_base.py index aec4d7106848..861e307e8926 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_base.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_base.py @@ -110,7 +110,7 @@ def GetHeaders( # pylint: disable=too-many-statements,too-many-branches ): """Gets HTTP request headers. - :param cosmos_client_connection.CosmosClient cosmos_client: + :param _cosmos_client_connection.CosmosClientConnection cosmos_client_connection: :param dict default_headers: :param str verb: :param str path: @@ -229,10 +229,11 @@ def GetHeaders( # pylint: disable=too-many-statements,too-many-branches headers[http_constants.HttpHeaders.PopulateQueryMetrics] = options["populateQueryMetrics"] if options.get("responseContinuationTokenLimitInKb"): - headers[http_constants.HttpHeaders.ResponseContinuationTokenLimitInKb] = options["responseContinuationTokenLimitInKb"] # pylint: disable=line-too-long + headers[http_constants.HttpHeaders.ResponseContinuationTokenLimitInKb] = options[ + "responseContinuationTokenLimitInKb"] if cosmos_client_connection.master_key: - #formatedate guarantees RFC 1123 date format regardless of current locale + # formatedate guarantees RFC 1123 date format regardless of current locale headers[http_constants.HttpHeaders.XDate] = formatdate(timeval=None, localtime=False, usegmt=True) if cosmos_client_connection.master_key or cosmos_client_connection.resource_tokens: @@ -491,7 +492,7 @@ def IsItemContainerLink(link): # pylint: disable=too-many-return-statements return True -def GetItemContainerInfo(self_link, alt_content_path, id_from_response): +def GetItemContainerInfo(self_link, alt_content_path, resource_id): """Given the self link and alt_content_path from the response header and result extract the collection name and collection id. @@ -521,13 +522,13 @@ def GetItemContainerInfo(self_link, alt_content_path, id_from_response): # this is a collection request index_second_slash = IndexOfNth(alt_content_path, "/", 2) if index_second_slash == -1: - collection_name = alt_content_path + "/colls/" + urllib_quote(id_from_response) + collection_name = alt_content_path + "/colls/" + urllib_quote(resource_id) return collection_id, collection_name collection_name = alt_content_path return collection_id, collection_name raise ValueError( "Response Not from Server Partition, self_link: {0}, alt_content_path: {1}, id: {2}".format( - self_link, alt_content_path, id_from_response + self_link, alt_content_path, resource_id ) ) @@ -700,11 +701,11 @@ def _set_throughput_options(offer: Union[int, ThroughputProperties], request_opt if offer.offer_throughput: request_options["offerThroughput"] = offer.offer_throughput - except AttributeError: + except AttributeError as e: if isinstance(offer, int): request_options["offerThroughput"] = offer else: - raise TypeError("offer_throughput must be int or an instance of ThroughputProperties") + raise TypeError("offer_throughput must be int or an instance of ThroughputProperties") from e def _deserialize_throughput(throughput: list) -> Any: @@ -739,18 +740,21 @@ def _replace_throughput(throughput: Union[int, ThroughputProperties], new_throug if throughput.offer_throughput: new_throughput_properties["content"]["offerThroughput"] = throughput.offer_throughput - except AttributeError: + except AttributeError as e: if isinstance(throughput, int): new_throughput_properties["content"]["offerThroughput"] = throughput else: - raise TypeError("offer_throughput must be int or an instance of ThroughputProperties") + raise TypeError("offer_throughput must be int or an instance of ThroughputProperties") from e def _internal_resourcetype(resource_type: str) -> str: - """Partitionkey is used as the resource type for deleting all items by partition key in - other SDKs, but the colls resource type needs to be sent for the feature to work. In order to keep it consistent + """Partition key is used as the resource type for deleting all items by partition key in other SDKs, + but the colls (collection) resource type needs to be sent for the feature to work. In order to keep it consistent with other SDKs, we switch it here. + :param str resource_type: the resource type + :return: the resource type after checking if we're doing partition key delete. + :rtype: str """ - if resource_type.lower() == "partitionkey": + if resource_type.lower() == "partitionkey": return "colls" return resource_type diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_cosmos_client_connection.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_cosmos_client_connection.py index 315af7a77063..1900ada8678d 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_cosmos_client_connection.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_cosmos_client_connection.py @@ -31,7 +31,6 @@ from urllib3.util.retry import Retry from azure.core.paging import ItemPaged # type: ignore from azure.core import PipelineClient # type: ignore -from azure.core.exceptions import raise_with_traceback # type: ignore from azure.core.pipeline.policies import ( # type: ignore HTTPPolicy, ContentDecodePolicy, @@ -61,6 +60,8 @@ from ._cosmos_http_logging_policy import CosmosHttpLoggingPolicy ClassType = TypeVar("ClassType") + + # pylint: disable=protected-access @@ -245,26 +246,33 @@ def _set_client_consistency_level( @property def Session(self): - """Gets the session object from the client. """ + """Gets the session object from the client. + :returns: the session for the client + :rtype: _session.Session + """ return self.session @Session.setter def Session(self, session): """Sets a session object on the document client. - This will override the existing session + :param _session.Session session: the session to set """ self.session = session @property def WriteEndpoint(self): """Gets the current write endpoint for a geo-replicated database account. + :returns: the write endpoint for the database account + :rtype: str """ return self._global_endpoint_manager.get_write_endpoint() @property def ReadEndpoint(self): """Gets the current read endpoint for a geo-replicated database account. + :returns: the read endpoint for the database account + :rtype: str """ return self._global_endpoint_manager.get_read_endpoint() @@ -546,7 +554,7 @@ def UpsertUser(self, database_link, user, options=None, **kwargs): database_id, path = self._GetDatabaseIdWithPathForUser(database_link, user) return self.Upsert(user, path, "users", database_id, None, options, **kwargs) - def _GetDatabaseIdWithPathForUser(self, database_link, user): # pylint: disable=no-self-use + def _GetDatabaseIdWithPathForUser(self, database_link, user): CosmosClientConnection.__ValidateResource(user) path = base.GetPathFromLink(database_link, "users") database_id = base.GetResourceIdOrFullNameFromLink(database_link) @@ -690,7 +698,7 @@ def UpsertPermission(self, user_link, permission, options=None, **kwargs): path, user_id = self._GetUserIdWithPathForPermission(permission, user_link) return self.Upsert(permission, path, "permissions", user_id, None, options, **kwargs) - def _GetUserIdWithPathForPermission(self, permission, user_link): # pylint: disable=no-self-use + def _GetUserIdWithPathForPermission(self, permission, user_link): CosmosClientConnection.__ValidateResource(permission) path = base.GetPathFromLink(user_link, "permissions") user_id = base.GetResourceIdOrFullNameFromLink(user_link) @@ -860,14 +868,12 @@ def DeletePermission(self, permission_link, options=None, **kwargs): def ReadItems(self, collection_link, feed_options=None, response_hook=None, **kwargs): """Reads all documents in a collection. - :param str collection_link: - The link to the document collection. - :param dict feed_options: - - :return: - Query Iterable of Documents. - :rtype: - query_iterable.QueryIterable + :param str collection_link: The link to the document collection. + :param dict feed_options: The additional options for the operation. + :param response_hook: A callable invoked with the response metadata. + :type response_hook: Callable[[Dict[str, str], Dict[str, Any]] + :return: Query Iterable of Documents. + :rtype: query_iterable.QueryIterable """ if feed_options is None: @@ -888,13 +894,11 @@ def QueryItems( :param str database_or_container_link: The link to the database when using partitioning, otherwise link to the document collection. - :param (str or dict) query: - :param dict options: - The request options for the request. - :param str partition_key: - Partition key for the query(default value None) - :param response_hook: - A callable invoked with the response metadata + :param (str or dict) query: the query to be used + :param dict options: The request options for the request. + :param str partition_key: Partition key for the query(default value None) + :param response_hook: A callable invoked with the response metadata. + :type response_hook: Callable[[Dict[str, str], Dict[str, Any]] :return: Query Iterable of Documents. @@ -948,13 +952,10 @@ def fetch_fn(options): def QueryItemsChangeFeed(self, collection_link, options=None, response_hook=None, **kwargs): """Queries documents change feed in a collection. - :param str collection_link: - The link to the document collection. - :param dict options: - The request options for the request. - options may also specify partition key range id. - :param response_hook: - A callable invoked with the response metadata + :param str collection_link: The link to the document collection. + :param dict options: The request options for the request. + :param response_hook: A callable invoked with the response metadata. + :type response_hook: Callable[[Dict[str, str], Dict[str, Any]] :return: Query Iterable of Documents. @@ -977,16 +978,12 @@ def _QueryChangeFeed( ): """Queries change feed of a resource in a collection. - :param str collection_link: - The link to the document collection. - :param str resource_type: - The type of the resource. - :param dict options: - The request options for the request. - :param str partition_key_range_id: - Specifies partition key range id. - :param response_hook: - A callable invoked with the response metadata + :param str collection_link: The link to the document collection. + :param str resource_type: The type of the resource. + :param dict options: The request options for the request. + :param str partition_key_range_id: Specifies partition key range id. + :param response_hook: A callable invoked with the response metadata + :type response_hook: Callable[[Dict[str, str], Dict[str, Any]] :return: Query Iterable of Documents. @@ -1037,14 +1034,10 @@ def fetch_fn(options): def _ReadPartitionKeyRanges(self, collection_link, feed_options=None, **kwargs): """Reads Partition Key Ranges. - :param str collection_link: - The link to the document collection. - :param dict feed_options: - - :return: - Query Iterable of PartitionKeyRanges. - :rtype: - query_iterable.QueryIterable + :param str collection_link: The link to the document collection. + :param dict feed_options: The request options. + :return: Query Iterable of PartitionKeyRanges. + :rtype: query_iterable.QueryIterable """ if feed_options is None: @@ -1091,19 +1084,10 @@ def CreateItem(self, database_or_container_link, document, options=None, **kwarg :param str database_or_container_link: The link to the database when using partitioning, otherwise link to the document collection. - :param dict document: - The Azure Cosmos document to create. - :param dict options: - The request options for the request. - :param bool options['disableAutomaticIdGeneration']: - Disables the automatic id generation. If id is missing in the body and this - option is true, an error will be returned. - - :return: - The created Document. - :rtype: - dict - + :param dict document: The Azure Cosmos document to create. + :param dict options: The request options for the request. + :return: The created Document. + :rtype: dict """ # Python's default arguments are evaluated once when the function is defined, # not each time the function is called (like it is in say, Ruby). This means @@ -1131,19 +1115,10 @@ def UpsertItem(self, database_or_container_link, document, options=None, **kwarg :param str database_or_container_link: The link to the database when using partitioning, otherwise link to the document collection. - :param dict document: - The Azure Cosmos document to upsert. - :param dict options: - The request options for the request. - :param bool options['disableAutomaticIdGeneration']: - Disables the automatic id generation. If id is missing in the body and this - option is true, an error will be returned. - - :return: - The upserted Document. - :rtype: - dict - + :param dict document: The Azure Cosmos document to upsert. + :param dict options: The request options for the request. + :return: The upserted Document. + :rtype: dict """ # Python's default arguments are evaluated once when the function is defined, # not each time the function is called (like it is in say, Ruby). This means @@ -1315,7 +1290,7 @@ def UpsertTrigger(self, collection_link, trigger, options=None, **kwargs): collection_id, path, trigger = self._GetContainerIdWithPathForTrigger(collection_link, trigger) return self.Upsert(trigger, path, "triggers", collection_id, None, options, **kwargs) - def _GetContainerIdWithPathForTrigger(self, collection_link, trigger): # pylint: disable=no-self-use + def _GetContainerIdWithPathForTrigger(self, collection_link, trigger): CosmosClientConnection.__ValidateResource(trigger) trigger = trigger.copy() if trigger.get("serverScript"): @@ -1443,7 +1418,7 @@ def UpsertUserDefinedFunction(self, collection_link, udf, options=None, **kwargs collection_id, path, udf = self._GetContainerIdWithPathForUDF(collection_link, udf) return self.Upsert(udf, path, "udfs", collection_id, None, options, **kwargs) - def _GetContainerIdWithPathForUDF(self, collection_link, udf): # pylint: disable=no-self-use + def _GetContainerIdWithPathForUDF(self, collection_link, udf): CosmosClientConnection.__ValidateResource(udf) udf = udf.copy() if udf.get("serverScript"): @@ -1571,7 +1546,7 @@ def UpsertStoredProcedure(self, collection_link, sproc, options=None, **kwargs): collection_id, path, sproc = self._GetContainerIdWithPathForSproc(collection_link, sproc) return self.Upsert(sproc, path, "sprocs", collection_id, None, options, **kwargs) - def _GetContainerIdWithPathForSproc(self, collection_link, sproc): # pylint: disable=no-self-use + def _GetContainerIdWithPathForSproc(self, collection_link, sproc): CosmosClientConnection.__ValidateResource(sproc) sproc = sproc.copy() if sproc.get("serverScript"): @@ -1787,10 +1762,10 @@ def DeleteItem(self, document_link, options=None, **kwargs): return self.DeleteResource(path, "docs", document_id, None, options, **kwargs) def DeleteAllItemsByPartitionKey( - self, - collection_link, - options=None, - **kwargs + self, + collection_link, + options=None, + **kwargs ) -> None: """Exposes an API to delete all items with a single partition key without the user having to explicitly call delete on each record in the partition key. @@ -1809,7 +1784,7 @@ def DeleteAllItemsByPartitionKey( options = {} path = base.GetPathFromLink(collection_link) - #Specified url to perform background operation to delete all items by partition key + # Specified url to perform background operation to delete all items by partition key path = '{}{}/{}'.format(path, "operations", "partitionkeydelete") collection_id = base.GetResourceIdOrFullNameFromLink(collection_link) initial_headers = dict(self.default_headers) @@ -2106,11 +2081,9 @@ def fetch_fn(options): def GetDatabaseAccount(self, url_connection=None, **kwargs): """Gets database account info. - :return: - The Database Account. - :rtype: - documents.DatabaseAccount - + :param str url_connection: the endpoint used to get the database account + :return: The Database Account. + :rtype: documents.DatabaseAccount """ if url_connection is None: url_connection = self.url_connection @@ -2302,15 +2275,11 @@ def DeleteResource(self, path, typ, id, initial_headers, options=None, def __Get(self, path, request_params, req_headers, **kwargs): """Azure Cosmos 'GET' http request. - :params str url: - :params str path: - :params dict req_headers: - - :return: - Tuple of (result, headers). - :rtype: - tuple of (dict, dict) - + :param str path: the url to be used for the request. + :param ~azure.cosmos.RequestObject request_params: the request parameters. + :param Dict[str, Any] req_headers: the request headers. + :return: Tuple of (result, headers). + :rtype: tuple of (dict, dict) """ request = self.pipeline_client.get(url=path, headers=req_headers) return synchronized_request.SynchronizedRequest( @@ -2327,16 +2296,12 @@ def __Get(self, path, request_params, req_headers, **kwargs): def __Post(self, path, request_params, body, req_headers, **kwargs): """Azure Cosmos 'POST' http request. - :params str url: - :params str path: - :params (str, unicode, dict) body: - :params dict req_headers: - - :return: - Tuple of (result, headers). - :rtype: - tuple of (dict, dict) - + :param str path: the url to be used for the request. + :param ~azure.cosmos.RequestObject request_params: the request parameters. + :param Union[str, unicode, Dict[Any, Any]] body: the request body. + :param Dict[str, Any] req_headers: the request headers. + :return: Tuple of (result, headers). + :rtype: tuple of (dict, dict) """ request = self.pipeline_client.post(url=path, headers=req_headers) return synchronized_request.SynchronizedRequest( @@ -2353,16 +2318,12 @@ def __Post(self, path, request_params, body, req_headers, **kwargs): def __Put(self, path, request_params, body, req_headers, **kwargs): """Azure Cosmos 'PUT' http request. - :params str url: - :params str path: - :params (str, unicode, dict) body: - :params dict req_headers: - - :return: - Tuple of (result, headers). - :rtype: - tuple of (dict, dict) - + :param str path: the url to be used for the request. + :param ~azure.cosmos.RequestObject request_params: the request parameters. + :param Union[str, unicode, Dict[Any, Any]] body: the request body. + :param Dict[str, Any] req_headers: the request headers. + :return: Tuple of (result, headers). + :rtype: tuple of (dict, dict) """ request = self.pipeline_client.put(url=path, headers=req_headers) return synchronized_request.SynchronizedRequest( @@ -2379,16 +2340,12 @@ def __Put(self, path, request_params, body, req_headers, **kwargs): def __Patch(self, path, request_params, request_data, req_headers, **kwargs): """Azure Cosmos 'PATCH' http request. - :params str path: - :params ~azure.cosmos.RequestObject request_params: - :params dict request_data: - :params dict req_headers: - - :return: - Tuple of (result, headers). - :rtype: - tuple of (dict, dict) - + :param str path: the url to be used for the request. + :param ~azure.cosmos.RequestObject request_params: the request parameters. + :param Union[str, unicode, Dict[Any, Any]] request_data: the request body. + :param Dict[str, Any] req_headers: the request headers. + :return: Tuple of (result, headers). + :rtype: tuple of (dict, dict) """ request = self.pipeline_client.patch(url=path, headers=req_headers) return synchronized_request.SynchronizedRequest( @@ -2405,15 +2362,11 @@ def __Patch(self, path, request_params, request_data, req_headers, **kwargs): def __Delete(self, path, request_params, req_headers, **kwargs): """Azure Cosmos 'DELETE' http request. - :params str url: - :params str path: - :params dict req_headers: - - :return: - Tuple of (result, headers). - :rtype: - tuple of (dict, dict) - + :param str path: the url to be used for the request. + :param ~azure.cosmos.RequestObject request_params: the request parameters. + :param Dict[str, Any] req_headers: the request headers. + :return: Tuple of (result, headers). + :rtype: tuple of (dict, dict) """ request = self.pipeline_client.delete(url=path, headers=req_headers) return synchronized_request.SynchronizedRequest( @@ -2430,18 +2383,13 @@ def __Delete(self, path, request_params, req_headers, **kwargs): def QueryFeed(self, path, collection_id, query, options, partition_key_range_id=None, **kwargs): """Query Feed for Document Collection resource. - :param str path: - Path to the document collection. - :param str collection_id: - Id of the document collection. + :param str path: Path to the document collection. + :param str collection_id: Id of the document collection. :param (str or dict) query: - :param dict options: - The request options for the request. - :param str partition_key_range_id: - Partition key range id. - :rtype: - tuple - + :param dict options: The request options for the request. + :param str partition_key_range_id: Partition key range id. + :return: Tuple of (result, headers). + :rtype: tuple of (dict, dict) """ return ( self.__QueryFeed( @@ -2487,12 +2435,9 @@ def __QueryFeed( :param function response_hook: :param bool is_query_plan: Specifies if the call is to fetch query plan - - :rtype: - list - + :returns: A list of the queried resources. + :rtype: list :raises SystemError: If the query compatibility mode is undefined. - """ if options is None: options = {} @@ -2526,10 +2471,8 @@ def __GetBodiesFromQueryResult(result): if not is_query_plan: initial_headers[http_constants.HttpHeaders.IsQuery] = "true" - if ( - self._query_compatibility_mode == CosmosClientConnection._QueryCompatibilityMode.Default - or self._query_compatibility_mode == CosmosClientConnection._QueryCompatibilityMode.Query - ): + if (self._query_compatibility_mode in (CosmosClientConnection._QueryCompatibilityMode.Default, + CosmosClientConnection._QueryCompatibilityMode.Query)): initial_headers[http_constants.HttpHeaders.ContentType] = runtime_constants.MediaTypes.QueryJson elif self._query_compatibility_mode == CosmosClientConnection._QueryCompatibilityMode.SqlQuery: initial_headers[http_constants.HttpHeaders.ContentType] = runtime_constants.MediaTypes.SQL @@ -2635,7 +2578,7 @@ def __CheckAndUnifyQueryFormat(self, query_body): """Checks and unifies the format of the query body. :raises TypeError: If query_body is not of expected type (depending on the query compatibility mode). - :raises ValueError: If query_body is a dict but doesn\'t have valid query text. + :raises ValueError: If query_body is a dict but doesn't have valid query text. :raises SystemError: If the query compatibility mode is undefined. :param (str or dict) query_body: @@ -2645,10 +2588,8 @@ def __CheckAndUnifyQueryFormat(self, query_body): :rtype: dict or string """ - if ( - self._query_compatibility_mode == CosmosClientConnection._QueryCompatibilityMode.Default - or self._query_compatibility_mode == CosmosClientConnection._QueryCompatibilityMode.Query - ): + if (self._query_compatibility_mode in (CosmosClientConnection._QueryCompatibilityMode.Default, + CosmosClientConnection._QueryCompatibilityMode.Query)): if not isinstance(query_body, dict) and not isinstance(query_body, str): raise TypeError("query body must be a dict or string.") if isinstance(query_body, dict) and not query_body.get("query"): @@ -2676,8 +2617,8 @@ def __ValidateResource(resource): if id_[-1] == " ": raise ValueError("Id ends with a space.") - except AttributeError: - raise_with_traceback(TypeError, message="Id type must be a string.") + except AttributeError as e: + raise TypeError("Id type must be a string.") from e # Adds the partition key to options def _AddPartitionKey(self, collection_link, document, options): @@ -2761,13 +2702,9 @@ def _UpdateSessionIfRequired(self, request_headers, response_result, response_he """ Updates session if necessary. - :param dict response_result: - :param dict response_headers: - :param dict response_headers - - :return: - None, but updates the client session if necessary. - + :param dict request_headers: The request headers. + :param dict response_result: The response result. + :param dict response_headers: The response headers. """ # if this request was made with consistency level as session, then update the session diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_default_retry_policy.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_default_retry_policy.py index c42acadfae37..3223fe40d716 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_default_retry_policy.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_default_retry_policy.py @@ -66,11 +66,11 @@ def needsRetry(self, error_code): return False def ShouldRetry(self, exception): - """Returns true if should retry based on the passed-in exception. - - :param (exceptions.CosmosHttpResponseError instance) exception: - :rtype: boolean + """Returns true if the request should retry based on the passed-in exception. + :param exceptions.CosmosHttpResponseError exception: + :returns: a boolean stating whether the request should be retried + :rtype: bool """ if (self.current_retry_attempt_count < self._max_retry_attempt_count) and self.needsRetry( exception.status_code diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_endpoint_discovery_retry_policy.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_endpoint_discovery_retry_policy.py index 2f0ec533a6f1..521ea5b900e0 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_endpoint_discovery_retry_policy.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_endpoint_discovery_retry_policy.py @@ -60,11 +60,11 @@ def __init__(self, connection_policy, global_endpoint_manager, *args): self.request.route_to_location(self.location_endpoint) def ShouldRetry(self, exception): # pylint: disable=unused-argument - """Returns true if should retry based on the passed-in exception. - - :param (exceptions.CosmosHttpResponseError instance) exception: - :rtype: boolean + """Returns true if the request should retry based on the passed-in exception. + :param exceptions.CosmosHttpResponseError exception: + :returns: a boolean stating whether the request should be retried + :rtype: bool """ if not self.connection_policy.EnableEndpointDiscovery: return False diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/aio/_queue_async_helper.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/aio/_queue_async_helper.py index ae81deb5a7cb..0633baef28b3 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/aio/_queue_async_helper.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/aio/_queue_async_helper.py @@ -20,13 +20,22 @@ # SOFTWARE. async def heap_push(heap, item, document_producer_comparator): - """Push item onto heap, maintaining the heap invariant.""" + """Push item onto heap, maintaining the heap invariant. + :param list heap: + :param Any item: + :param _PartitionKeyRangeDocumentProducerComparator document_producer_comparator: + """ heap.append(item) await _sift_down(heap, document_producer_comparator, 0, len(heap) - 1) async def heap_pop(heap, document_producer_comparator): - """Pop the smallest item off the heap, maintaining the heap invariant.""" + """Pop the smallest item off the heap, maintaining the heap invariant. + :param list heap: the heap to use for comparing + :param _PartitionKeyRangeDocumentProducerComparator document_producer_comparator: the document producer comparator + :returns: the popped item from the heap + :rtype: Any + """ last_elt = heap.pop() # raises appropriate IndexError if heap is empty if heap: return_item = heap[0] diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/aio/base_execution_context.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/aio/base_execution_context.py index 0b3d56cf5377..3f52e342d641 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/aio/base_execution_context.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/aio/base_execution_context.py @@ -83,7 +83,10 @@ async def _fetch_next_block(self): raise NotImplementedError def __aiter__(self): - """Returns itself as an iterator""" + """Returns itself as an iterator + :returns: Query as an iterator. + :rtype: Iterator + """ return self async def __anext__(self): @@ -109,6 +112,7 @@ async def __anext__(self): async def _fetch_items_helper_no_retries(self, fetch_function): """Fetches more items and doesn't retry on failure + :param Callable fetch_function: The function that fetches the items. :return: List of fetched items. :rtype: list """ diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/aio/document_producer.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/aio/document_producer.py index 1ec6bc13efd7..a26c309756d8 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/aio/document_producer.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/aio/document_producer.py @@ -116,7 +116,7 @@ class _PartitionKeyRangeDocumentProducerComparator(object): def __init__(self): pass - async def compare(self, doc_producer1, doc_producer2): # pylint: disable=no-self-use + async def compare(self, doc_producer1, doc_producer2): return _compare_helper( doc_producer1.get_target_range()["minInclusive"], doc_producer2.get_target_range()["minInclusive"] ) @@ -180,8 +180,7 @@ async def compare(orderby_item1, orderby_item2): :param dict orderby_item1: :param dict orderby_item2: - :return: - Integer comparison result. + :return: Integer comparison result. The comparator acts such that - if the types are different we get: Undefined value < Null < booleans < Numbers < Strings @@ -234,8 +233,8 @@ async def compare(self, doc_producer1, doc_producer2): If the peek results are equal based on the sort order, this comparator compares the target partition key range of the two DocumentProducers. - :param _DocumentProducer doc_producer1: first instance - :param _DocumentProducer doc_producer2: first instance + :param _DocumentProducer doc_producer1: first instance to be compared + :param _DocumentProducer doc_producer2: second instance to be compared :return: Integer value of compare result. positive integer if doc_producer1 > doc_producer2 diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/aio/endpoint_component.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/aio/endpoint_component.py index 40d0a4cc354d..eaee81b3a52a 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/aio/endpoint_component.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/aio/endpoint_component.py @@ -104,7 +104,7 @@ def __init__(self, execution_context): def make_hash(self, value): if isinstance(value, (set, tuple, list)): - return tuple([self.make_hash(v) for v in value]) + return tuple([self.make_hash(v) for v in value]) # pylint: disable=consider-using-generator if not isinstance(value, dict): if isinstance(value, numbers.Number): return float(value) diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/base_execution_context.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/base_execution_context.py index edd51d7c590d..f0769f6caf25 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/base_execution_context.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/base_execution_context.py @@ -81,7 +81,10 @@ def _fetch_next_block(self): raise NotImplementedError def __iter__(self): - """Returns itself as an iterator""" + """Returns itself as an iterator + :returns: Query as an iterator. + :rtype: Iterator + """ return self def __next__(self): @@ -107,6 +110,7 @@ def __next__(self): def _fetch_items_helper_no_retries(self, fetch_function): """Fetches more items and doesn't retry on failure + :param Callable fetch_function: The function that fetches the items. :return: List of fetched items. :rtype: list """ diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/document_producer.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/document_producer.py index 54aab209c41e..f362d8cd0c5a 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/document_producer.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/document_producer.py @@ -112,7 +112,7 @@ def _compare_helper(a, b): return (a > b) - (a < b) -class _PartitionKeyRangeDocumentProduerComparator(object): +class _PartitionKeyRangeDocumentProducerComparator(object): """ Provides a Comparator for document producers using the min value of the corresponding target partition. @@ -121,7 +121,7 @@ class _PartitionKeyRangeDocumentProduerComparator(object): def __init__(self): pass - def compare(self, doc_producer1, doc_producer2): # pylint: disable=no-self-use + def compare(self, doc_producer1, doc_producer2): return _compare_helper( doc_producer1.get_target_range()["minInclusive"], doc_producer2.get_target_range()["minInclusive"] ) @@ -185,8 +185,7 @@ def compare(orderby_item1, orderby_item2): :param dict orderby_item1: :param dict orderby_item2: - :return: - Integer comparison result. + :return: Integer comparison result. The comparator acts such that - if the types are different we get: Undefined value < Null < booleans < Numbers < Strings @@ -214,7 +213,7 @@ def _peek_order_by_items(peek_result): return peek_result["orderByItems"] -class _OrderByDocumentProducerComparator(_PartitionKeyRangeDocumentProduerComparator): +class _OrderByDocumentProducerComparator(_PartitionKeyRangeDocumentProducerComparator): """Provide a Comparator for document producers which respects orderby sort order. """ @@ -239,8 +238,8 @@ def compare(self, doc_producer1, doc_producer2): If the peek results are equal based on the sort order, this comparator compares the target partition key range of the two DocumentProducers. - :param _DocumentProducer doc_producers1: first instance - :param _DocumentProducer doc_producers2: first instance + :param _DocumentProducer doc_producer1: first instance to be compared + :param _DocumentProducer doc_producer2: second instance to be compared :return: Integer value of compare result. positive integer if doc_producers1 > doc_producers2 @@ -261,7 +260,7 @@ def compare(self, doc_producer1, doc_producer2): if self._sort_order[i] == "Descending": return -res - return _PartitionKeyRangeDocumentProduerComparator.compare(self, doc_producer1, doc_producer2) + return _PartitionKeyRangeDocumentProducerComparator.compare(self, doc_producer1, doc_producer2) def _validate_orderby_items(self, res1, res2): if len(res1) != len(res2): diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/endpoint_component.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/endpoint_component.py index ddbd29fe3905..bc607bd9094e 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/endpoint_component.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/endpoint_component.py @@ -111,7 +111,7 @@ def __init__(self, execution_context): def make_hash(self, value): if isinstance(value, (set, tuple, list)): - return tuple([self.make_hash(v) for v in value]) + return tuple([self.make_hash(v) for v in value]) # pylint: disable=consider-using-generator if not isinstance(value, dict): if isinstance(value, numbers.Number): return float(value) diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/multi_execution_aggregator.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/multi_execution_aggregator.py index d0ed0b78bee6..b69d3cb4d250 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/multi_execution_aggregator.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/multi_execution_aggregator.py @@ -77,7 +77,7 @@ def __init__(self, client, resource_link, query, options, partitioned_query_ex_i if self._sort_orders: self._document_producer_comparator = document_producer._OrderByDocumentProducerComparator(self._sort_orders) else: - self._document_producer_comparator = document_producer._PartitionKeyRangeDocumentProduerComparator() + self._document_producer_comparator = document_producer._PartitionKeyRangeDocumentProducerComparator() # will be a list of (partition_min, partition_max) tuples targetPartitionRanges = self._get_target_partition_key_range() diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/query_execution_info.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/query_execution_info.py index 748155d863d5..e91c3dccc6ca 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/query_execution_info.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/query_execution_info.py @@ -49,41 +49,57 @@ def __init__(self, query_execution_info): def get_top(self): """Returns the top count (if any) or None. + :returns: The top count. + :rtype: int """ return self._extract(_PartitionedQueryExecutionInfo.TopPath) def get_limit(self): """Returns the limit count (if any) or None. + :returns: The limit count. + :rtype: int """ return self._extract(_PartitionedQueryExecutionInfo.LimitPath) def get_offset(self): """Returns the offset count (if any) or None. + :returns: The offset count. + :rtype: int """ return self._extract(_PartitionedQueryExecutionInfo.OffsetPath) def get_distinct_type(self): - """Returns the offset count (if any) or None. + """Returns the distinct type (if any) or None. + :returns: The distinct type. + :rtype: str """ return self._extract(_PartitionedQueryExecutionInfo.DistinctTypePath) def get_order_by(self): """Returns order by items (if any) or None. + :returns: The order by items. + :rtype: list """ return self._extract(_PartitionedQueryExecutionInfo.OrderByPath) def get_aggregates(self): """Returns aggregators (if any) or None. + :returns: The aggregate items. + :rtype: list """ return self._extract(_PartitionedQueryExecutionInfo.AggregatesPath) def get_query_ranges(self): """Returns query partition ranges (if any) or None. + :returns: The query ranges. + :rtype: list """ return self._extract(_PartitionedQueryExecutionInfo.QueryRangesPath) def get_rewritten_query(self): """Returns rewritten query or None (if any). + :returns: The rewritten query. + :rtype: str """ rewrittenQuery = self._extract(_PartitionedQueryExecutionInfo.RewrittenQueryPath) if rewrittenQuery is not None: @@ -118,7 +134,6 @@ def has_rewritten_query(self): return self.get_rewritten_query() is not None def _extract(self, path): - item = self._query_execution_info if isinstance(path, str): return item.get(path) diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_global_endpoint_manager.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_global_endpoint_manager.py index 5ccb41e6ce54..99394b3f9422 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_global_endpoint_manager.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_global_endpoint_manager.py @@ -57,7 +57,7 @@ def __init__(self, client): self.refresh_lock = threading.RLock() self.last_refresh_time = 0 - def get_refresh_time_interval_in_ms_stub(self): # pylint: disable=no-self-use + def get_refresh_time_interval_in_ms_stub(self): return constants._Constants.DefaultUnavailableLocationExpirationTime def get_write_endpoint(self): @@ -119,6 +119,8 @@ def _GetDatabaseAccount(self, **kwargs): First tries by using the default endpoint, and if that doesn't work, use the endpoints for the preferred locations in the order they are specified, to get the database account. + :returns: A `DatabaseAccount` instance representing the Cosmos DB Database Account. + :rtype: ~azure.cosmos.DatabaseAccount """ try: database_account = self._GetDatabaseAccountStub(self.DefaultEndpoint, **kwargs) @@ -141,8 +143,11 @@ def _GetDatabaseAccount(self, **kwargs): def _GetDatabaseAccountStub(self, endpoint, **kwargs): """Stub for getting database account from the client. - This can be used for mocking purposes as well. + + :param str endpoint: the endpoint being used to get the database account + :returns: A `DatabaseAccount` instance representing the Cosmos DB Database Account. + :rtype: ~azure.cosmos.DatabaseAccount """ return self.Client.GetDatabaseAccount(endpoint, **kwargs) diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_gone_retry_policy.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_gone_retry_policy.py index 78ebaab65bc8..d9b27e97403a 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_gone_retry_policy.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_gone_retry_policy.py @@ -37,10 +37,11 @@ def __init__(self, client, *args): self.exception = None def ShouldRetry(self, exception): - """Returns true if should retry based on the passed-in exception. + """Returns true if the request should retry based on the passed-in exception. :param (exceptions.CosmosHttpResponseError instance) exception: - :rtype: boolean + :returns: a boolean stating whether the request should be retried + :rtype: bool """ self.exception = exception # needed for pylint diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_location_cache.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_location_cache.py index e3f550f03a9e..cc8bb604e0f7 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_location_cache.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_location_cache.py @@ -56,7 +56,7 @@ def get_endpoint_by_location(locations): class LocationCache(object): # pylint: disable=too-many-public-methods,too-many-instance-attributes - def current_time_millis(self): # pylint: disable=no-self-use + def current_time_millis(self): return int(round(time.time() * 1000)) def __init__( @@ -187,7 +187,7 @@ def should_refresh_endpoints(self): # pylint: disable=too-many-return-statement def clear_stale_endpoint_unavailability_info(self): new_location_unavailability_info = {} if self.location_unavailability_info_by_endpoint: - for unavailable_endpoint in self.location_unavailability_info_by_endpoint: + for unavailable_endpoint in self.location_unavailability_info_by_endpoint: #pylint: disable=consider-using-dict-items unavailability_info = self.location_unavailability_info_by_endpoint[unavailable_endpoint] if not ( unavailability_info @@ -319,7 +319,7 @@ def get_preferred_available_endpoints( def can_use_multiple_write_locations(self): return self.use_multiple_write_locations and self.enable_multiple_writable_locations - def can_use_multiple_write_locations_for_request(self, request): + def can_use_multiple_write_locations_for_request(self, request): # pylint: disable=name-too-long return self.can_use_multiple_write_locations() and ( request.resource_type == http_constants.ResourceType.Document or ( diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_partition.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_partition.py index bd98125c456a..ccb79401a107 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_partition.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_partition.py @@ -23,6 +23,7 @@ database service. """ + class Partition(object): """A class that holds the hash value and node name for a partition. """ @@ -47,6 +48,11 @@ def __lt__(self, other): def CompareTo(self, other_hash_value): """Compare the passed hash value with the hash value of this object. + :param List[int] other_hash_value: the hash value to be compared + :returns: an integer stating the result of the comparison + -1 if other_hash_value is greater than self.hash_value, 1 if other_hash_value is less than self.hash_value, + 0 if they're both equal + :rtype: int """ if len(self.hash_value) != len(other_hash_value): raise ValueError("Length of hashes doesn't match.") diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_query_iterable.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_query_iterable.py index 96eaffba221e..67f96655e942 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_query_iterable.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_query_iterable.py @@ -92,6 +92,7 @@ def _fetch_next(self, *args): # pylint: disable=unused-argument This method only exists for backward compatibility reasons. (Because QueryIterable has exposed fetch_next_block api). + :param Any args: :return: List of results. :rtype: list """ diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_range.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_range.py index 88a8d640dafb..6b8b620f1673 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_range.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_range.py @@ -54,7 +54,10 @@ def __lt__(self, other): return self.low < other.low or self.high < other.high def Contains(self, other): - """Check if the passed parameter is in the range of this object. + """Check if the passed in partition key is in the range of this object. + :param Union[_range.Range, str] other: the other range or partition key being checked + :returns: a boolean stating whether the parameter is in the range of this object. + :rtype: bool """ if other is None: raise ValueError("other is None.") @@ -65,6 +68,9 @@ def Contains(self, other): def Intersect(self, other): """Check if the passed parameter intersects the range of this object. + :param _range.Range other: the other partition key range being checked + :returns: a boolean stating whether the partition key range passed intersects the range of this object. + :rtype: bool """ if isinstance(other, Range): max_low = self.low if (self.low >= other.low) else other.low diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_range_partition_resolver.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_range_partition_resolver.py index 160a7e961e3a..bea7631bc7cf 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_range_partition_resolver.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_range_partition_resolver.py @@ -66,13 +66,13 @@ def ResolveForCreate(self, document): def ResolveForRead(self, partition_key): """Resolves the collection for reading/querying the documents based on the partition key. - :param dict document: The document to be read/queried. + :param str partition_key: The partition key to be used. :return: Collection Self link(s) or Name based link(s) which should handle the Read operation. :rtype: list """ intersecting_ranges = self._GetIntersectingRanges(partition_key) - collection_links = list() + collection_links = [] for keyrange in intersecting_ranges: collection_links.append(self.partition_map.get(keyrange)) @@ -80,6 +80,9 @@ def ResolveForRead(self, partition_key): def _GetContainingRange(self, partition_key): """Get the containing range based on the partition key. + :param str partition_key: The partition key to be used. + :returns: The containing key range. + :rtype: str """ for keyrange in self.partition_map.keys(): if keyrange.Contains(partition_key): @@ -89,6 +92,9 @@ def _GetContainingRange(self, partition_key): def _GetIntersectingRanges(self, partition_key): """Get the intersecting ranges based on the partition key. + :param str partition_key: The partition key to be used. + :returns: the set of intersecting ranges for the partition key. + :rtype: set """ partitionkey_ranges = set() intersecting_ranges = set() diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_request_object.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_request_object.py index 1f574e82b421..539d0768d3cd 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_request_object.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_request_object.py @@ -28,12 +28,12 @@ def __init__(self, resource_type, operation_type, endpoint_override=None): self.resource_type = resource_type self.operation_type = operation_type self.endpoint_override = endpoint_override - self.should_clear_session_token_on_session_read_failure = False + self.should_clear_session_token_on_session_read_failure = False # pylint: disable=name-too-long self.use_preferred_locations = None self.location_index_to_route = None self.location_endpoint_to_route = None - def route_to_location_with_preferred_location_flag(self, location_index, use_preferred_locations): + def route_to_location_with_preferred_location_flag(self, location_index, use_preferred_locations): # pylint: disable=name-too-long self.location_index_to_route = location_index self.use_preferred_locations = use_preferred_locations self.location_endpoint_to_route = None diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_resource_throttle_retry_policy.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_resource_throttle_retry_policy.py index eb302f279baa..fcbd57d4bf2f 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_resource_throttle_retry_policy.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_resource_throttle_retry_policy.py @@ -35,10 +35,11 @@ def __init__(self, max_retry_attempt_count, fixed_retry_interval_in_milliseconds self.cumulative_wait_time_in_milliseconds = 0 def ShouldRetry(self, exception): - """Returns true if should retry based on the passed-in exception. + """Returns true if the request should retry based on the passed-in exception. - :param (exceptions.CosmosHttpResponseError instance) exception: - :rtype: boolean + :param exceptions.CosmosHttpResponseError exception: + :returns: a boolean stating whether the request should be retried + :rtype: bool """ if self.current_retry_attempt_count < self._max_retry_attempt_count: self.current_retry_attempt_count += 1 diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_retry_utility.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_retry_utility.py index b5c6aebb2bea..1c342fff7e48 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_retry_utility.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_retry_utility.py @@ -49,9 +49,9 @@ def Execute(client, global_endpoint_manager, function, *args, **kwargs): Instance of _GlobalEndpointManager class :param function function: Function to be called wrapped with retries - :param (non-keyworded, variable number of arguments list) *args: - :param (keyworded, variable number of arguments list) **kwargs: - + :param list args: + :returns: the result of running the passed in function as a (result, headers) tuple + :rtype: tuple of (dict, dict) """ # instantiate all retry policies here to be applied for each request execution endpointDiscovery_retry_policy = _endpoint_discovery_retry_policy.EndpointDiscoveryRetryPolicy( @@ -76,9 +76,9 @@ def Execute(client, global_endpoint_manager, function, *args, **kwargs): ) while True: + client_timeout = kwargs.get('timeout') + start_time = time.time() try: - client_timeout = kwargs.get('timeout') - start_time = time.time() if args: result = ExecuteFunction(function, global_endpoint_manager, *args, **kwargs) else: @@ -110,7 +110,7 @@ def Execute(client, global_endpoint_manager, function, *args, **kwargs): retry_policy = sessionRetry_policy elif exceptions._partition_range_is_gone(e): retry_policy = partition_key_range_gone_retry_policy - elif e.status_code == StatusCodes.REQUEST_TIMEOUT or e.status_code == StatusCodes.SERVICE_UNAVAILABLE: + elif e.status_code in (StatusCodes.REQUEST_TIMEOUT, e.status_code == StatusCodes.SERVICE_UNAVAILABLE): retry_policy = timeout_failover_retry_policy # If none of the retry policies applies or there is no retry needed, set the @@ -139,6 +139,10 @@ def Execute(client, global_endpoint_manager, function, *args, **kwargs): def ExecuteFunction(function, *args, **kwargs): """Stub method so that it can be used for mocking purposes as well. + :param Callable function: the function to execute. + :param list args: the explicit arguments for the function. + :returns: the result of executing the function with the passed in arguments + :rtype: tuple(dict, dict) """ return function(*args, **kwargs) @@ -184,8 +188,8 @@ def send(self, request): response = None retry_settings = self.configure_retries(request.context.options) while retry_active: + start_time = time.time() try: - start_time = time.time() _configure_timeout(request, absolute_timeout, per_request_timeout) response = self.next.send(request) diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_session.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_session.py index 35cbb216f2e2..2562eafe3dd1 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_session.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_session.py @@ -133,7 +133,7 @@ def set_session_token(self, response_result, response_headers): # update session token in collection rid to session token map if collection_rid in self.rid_to_session_token: # we need to update the session tokens for 'this' collection - for id_ in parsed_tokens: + for id_ in parsed_tokens: # pylint: disable=consider-using-dict-items old_session_token = ( self.rid_to_session_token[collection_rid][id_] if id_ in self.rid_to_session_token[collection_rid] diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_session_retry_policy.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_session_retry_policy.py index f92d65c62791..15709582eea8 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_session_retry_policy.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_session_retry_policy.py @@ -61,10 +61,11 @@ def __init__(self, endpoint_discovery_enable, global_endpoint_manager, *args): self.request.route_to_location(self.location_endpoint) def ShouldRetry(self, _exception): - """Returns true if should retry based on the passed-in exception. + """Returns true if the request should retry based on the passed-in exception. - :param (exceptions.CosmosHttpResponseError instance) exception: - :rtype: boolean + :param exceptions.CosmosHttpResponseError _exception: + :returns: a boolean stating whether the request should be retried + :rtype: bool """ self.session_token_retry_count += 1 # clear previous location-based routing directive diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_synchronized_request.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_synchronized_request.py index 79518497ac10..949ae8fe0516 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_synchronized_request.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_synchronized_request.py @@ -36,6 +36,8 @@ def _is_readable_stream(obj): """Checks whether obj is a file-like readable stream. + :param Union[str, unicode, file-like stream object, dict, list, None] obj: the object to be checked. + :returns: whether the object is a file-like readable stream. :rtype: boolean """ if hasattr(obj, "read") and callable(getattr(obj, "read")): @@ -49,10 +51,9 @@ def _request_body_from_data(data): When `data` is dict and list into unicode string; otherwise return `data` without making any change. - :param (str, unicode, file-like stream object, dict, list or None) data: - - :rtype: - str, unicode, file-like stream object, or None + :param Union[str, unicode, file-like stream object, dict, list, None] data: + :returns: the json dump data. + :rtype: Union[str, unicode, file-like stream object, None] """ if data is None or isinstance(data, str) or _is_readable_stream(data): @@ -161,7 +162,7 @@ def _Request(global_endpoint_manager, request_params, connection_policy, pipelin raise DecodeError( message="Failed to decode JSON data: {}".format(e), response=response, - error=e) + error=e) from e return result, headers @@ -188,11 +189,8 @@ def SynchronizedRequest( :param _GlobalEndpointManager global_endpoint_manager: :param documents.ConnectionPolicy connection_policy: :param azure.core.PipelineClient pipeline_client: PipelineClient to process the request. - :param str method: - :param str path: - :param (str, unicode, file-like stream object, dict, list or None) request_data: - :param dict query_params: - :param dict headers: + :param HttpRequest request: the HTTP request to be sent + :param (str, unicode, file-like stream object, dict, list or None) request_data: the data to be sent in the request :return: tuple of (result, headers) :rtype: tuple of (dict dict) """ @@ -202,7 +200,7 @@ def SynchronizedRequest( elif request.data is None: request.headers[http_constants.HttpHeaders.ContentLength] = 0 - # Pass _Request function with it's parameters to retry_utility's Execute method that wraps the call with retries + # Pass _Request function with its parameters to retry_utility's Execute method that wraps the call with retries return _retry_utility.Execute( client, global_endpoint_manager, diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_timeout_failover_retry_policy.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_timeout_failover_retry_policy.py index ddd279d9f38d..98e27c76fbcd 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_timeout_failover_retry_policy.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_timeout_failover_retry_policy.py @@ -49,11 +49,11 @@ def needsRetry(self): return False def ShouldRetry(self, _exception): - """Returns true if should retry based on the passed-in exception. - - :param (exceptions.CosmosHttpResponseError instance) _exception: - :rtype: boolean + """Returns true if the request should retry based on the passed-in exception. + :param exceptions.CosmosHttpResponseError _exception: + :returns: a boolean stating whether the request should be retried + :rtype: bool """ if not self.needsRetry(): return False diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_asynchronous_request.py b/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_asynchronous_request.py index fb8560edc051..a3e8b25a823c 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_asynchronous_request.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_asynchronous_request.py @@ -130,7 +130,7 @@ async def _Request(global_endpoint_manager, request_params, connection_policy, p raise DecodeError( message="Failed to decode JSON data: {}".format(e), response=response, - error=e) + error=e) from e return result, headers @@ -157,11 +157,8 @@ async def AsynchronousRequest( :param _GlobalEndpointManager global_endpoint_manager: :param documents.ConnectionPolicy connection_policy: :param azure.core.PipelineClient pipeline_client: PipelineClient to process the request. - :param str method: - :param str path: + :param HttpRequest request: the HTTP request to be sent :param (str, unicode, file-like stream object, dict, list or None) request_data: - :param dict query_params: - :param dict headers: :return: tuple of (result, headers) :rtype: tuple of (dict dict) """ @@ -171,7 +168,7 @@ async def AsynchronousRequest( elif request.data is None: request.headers[http_constants.HttpHeaders.ContentLength] = 0 - # Pass _Request function with it's parameters to retry_utility's Execute method that wraps the call with retries + # Pass _Request function with its parameters to retry_utility's Execute method that wraps the call with retries return await _retry_utility_async.ExecuteAsync( client, global_endpoint_manager, diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_auth_policy_async.py b/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_auth_policy_async.py index f5913f5cf56a..5fde75a5934c 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_auth_policy_async.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_auth_policy_async.py @@ -14,7 +14,12 @@ async def await_result(func, *args, **kwargs): - """If func returns an awaitable, await it.""" + """If func returns an awaitable, await it. + :param Callable func: The function to be awaited. + :param List[Any] args: The explicit arguments for the function. + :returns: The result from awaiting the function. + :rtype: HttpResponse + """ result = func(*args, **kwargs) if hasattr(result, "__await__"): # type ignore on await: https://github.com/python/mypy/issues/7587 @@ -117,6 +122,8 @@ async def send(self, request: "PipelineRequest") -> "PipelineResponse": :param request: The pipeline request object :type request: ~azure.core.pipeline.PipelineRequest + :returns: The result of sending the request. + :rtype: ~azure.core.pipeline.PipelineResponse """ await await_result(self.on_request, request) try: @@ -149,9 +156,10 @@ async def on_challenge(self, request: "PipelineRequest", response: "PipelineResp :param ~azure.core.pipeline.PipelineRequest request: the request which elicited an authentication challenge :param ~azure.core.pipeline.PipelineResponse response: the resource provider's response - :returns: a bool indicating whether the policy should send the request + :returns: a boolean indicating whether the policy should send the request + :rtype: bool """ - # pylint:disable=unused-argument,no-self-use + # pylint:disable=unused-argument return False def on_response(self, request: PipelineRequest, response: PipelineResponse) -> Union[None, Awaitable[None]]: @@ -171,5 +179,5 @@ def on_exception(self, request: PipelineRequest) -> None: :param request: The Pipeline request object :type request: ~azure.core.pipeline.PipelineRequest """ - # pylint: disable=no-self-use,unused-argument + # pylint: disable=unused-argument return diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_container.py b/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_container.py index f376c1290f3f..2e638f5dd783 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_container.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_container.py @@ -538,7 +538,7 @@ async def patch_item( patch_operations: List[Dict[str, Any]], **kwargs: Any ) -> Dict[str, Any]: - """ **Provisional method** Patches the specified item with the provided operations if it + """ Patches the specified item with the provided operations if it exists in the container. If the item does not already exist in the container, an exception is raised. diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_cosmos_client.py b/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_cosmos_client.py index 9f68ab581afc..e3b85f481cd1 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_cosmos_client.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_cosmos_client.py @@ -95,7 +95,7 @@ class CosmosClient(object): # pylint: disable=client-accepts-api-version-keywor Use this client to configure and execute requests to the Azure Cosmos DB service. - Its recommended to maintain a single instance of CosmosClient per lifetime of the application which enables + It's recommended to maintain a single instance of CosmosClient per lifetime of the application which enables efficient connection management and performance. CosmosClient initialization is a heavy operation - don't use initialization CosmosClient instances as diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_cosmos_client_connection_async.py b/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_cosmos_client_connection_async.py index a6d5f34505f0..f1545c1727ba 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_cosmos_client_connection_async.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_cosmos_client_connection_async.py @@ -32,7 +32,6 @@ from urllib3.util.retry import Retry from azure.core.async_paging import AsyncItemPaged from azure.core import AsyncPipelineClient -from azure.core.exceptions import raise_with_traceback # type: ignore from azure.core.pipeline.policies import ( AsyncHTTPPolicy, ContentDecodePolicy, @@ -215,7 +214,10 @@ def __init__( @property def _Session(self): - """Gets the session object from the client. """ + """Gets the session object from the client. + :returns: the session for the client. + :rtype: _session.Session + """ return self.session @_Session.setter @@ -223,23 +225,27 @@ def _Session(self, session): """Sets a session object on the document client. This will override the existing session + :param _session.Session session: the client session to set. """ self.session = session @property def _WriteEndpoint(self): """Gets the current write endpoint for a geo-replicated database account. + :returns: the write endpoint for the database account + :rtype: str """ return self._global_endpoint_manager.get_write_endpoint() @property def _ReadEndpoint(self): """Gets the current read endpoint for a geo-replicated database account. + :returns: the read endpoint for the database account + :rtype: str """ return self._global_endpoint_manager.get_read_endpoint() async def _setup(self): - if 'database_account' not in self._setup_kwargs: database_account = await self._global_endpoint_manager._GetDatabaseAccount( **self._setup_kwargs) @@ -283,13 +289,13 @@ def _check_if_account_session_consistency( return consistency_level - def _GetDatabaseIdWithPathForUser(self, database_link, user): # pylint: disable=no-self-use + def _GetDatabaseIdWithPathForUser(self, database_link, user): CosmosClientConnection.__ValidateResource(user) path = base.GetPathFromLink(database_link, "users") database_id = base.GetResourceIdOrFullNameFromLink(database_link) return database_id, path - def _GetContainerIdWithPathForSproc(self, collection_link, sproc): # pylint: disable=no-self-use + def _GetContainerIdWithPathForSproc(self, collection_link, sproc): CosmosClientConnection.__ValidateResource(sproc) sproc = sproc.copy() if sproc.get("serverScript"): @@ -300,7 +306,7 @@ def _GetContainerIdWithPathForSproc(self, collection_link, sproc): # pylint: di collection_id = base.GetResourceIdOrFullNameFromLink(collection_link) return collection_id, path, sproc - def _GetContainerIdWithPathForTrigger(self, collection_link, trigger): # pylint: disable=no-self-use + def _GetContainerIdWithPathForTrigger(self, collection_link, trigger): CosmosClientConnection.__ValidateResource(trigger) trigger = trigger.copy() if trigger.get("serverScript"): @@ -312,7 +318,7 @@ def _GetContainerIdWithPathForTrigger(self, collection_link, trigger): # pylint collection_id = base.GetResourceIdOrFullNameFromLink(collection_link) return collection_id, path, trigger - def _GetContainerIdWithPathForUDF(self, collection_link, udf): # pylint: disable=no-self-use + def _GetContainerIdWithPathForUDF(self, collection_link, udf): CosmosClientConnection.__ValidateResource(udf) udf = udf.copy() if udf.get("serverScript"): @@ -327,6 +333,7 @@ def _GetContainerIdWithPathForUDF(self, collection_link, udf): # pylint: disabl async def GetDatabaseAccount(self, url_connection=None, **kwargs): """Gets database account info. + :param str url_connection: the endpoint used to get the database account :return: The Database Account. :rtype: @@ -376,7 +383,6 @@ async def CreateDatabase(self, database, options=None, **kwargs): The Azure Cosmos database to create. :param dict options: The request options for the request. - :return: The Database that was created. :rtype: dict @@ -398,7 +404,6 @@ async def CreateUser(self, database_link, user, options=None, **kwargs): The Azure Cosmos user to create. :param dict options: The request options for the request. - :return: The created User. :rtype: @@ -420,7 +425,6 @@ async def CreateContainer(self, database_link, collection, options=None, **kwarg The Azure Cosmos collection to create. :param dict options: The request options for the request. - :return: The Collection that was created. :rtype: dict @@ -442,10 +446,6 @@ async def CreateItem(self, database_or_container_link, document, options=None, * The Azure Cosmos document to create. :param dict options: The request options for the request. - :param bool options['disableAutomaticIdGeneration']: - Disables the automatic id generation. If id is missing in the body and this - option is true, an error will be returned. - :return: The created Document. :rtype: @@ -482,7 +482,6 @@ async def CreatePermission(self, user_link, permission, options=None, **kwargs): The Azure Cosmos user permission to create. :param dict options: The request options for the request. - :return: The created Permission. :rtype: @@ -503,7 +502,6 @@ async def CreateUserDefinedFunction(self, collection_link, udf, options=None, ** :param str udf: :param dict options: The request options for the request. - :return: The created UDF. :rtype: @@ -524,7 +522,6 @@ async def CreateTrigger(self, collection_link, trigger, options=None, **kwargs): :param dict trigger: :param dict options: The request options for the request. - :return: The created Trigger. :rtype: @@ -545,7 +542,6 @@ async def CreateStoredProcedure(self, collection_link, sproc, options=None, **kw :param str sproc: :param dict options: The request options for the request. - :return: The created Stored Procedure. :rtype: @@ -567,7 +563,6 @@ async def ExecuteStoredProcedure(self, sproc_link, params, options=None, **kwarg List or None :param dict options: The request options for the request. - :return: The Stored Procedure response. :rtype: @@ -593,7 +588,7 @@ async def ExecuteStoredProcedure(self, sproc_link, params, options=None, **kwarg return result async def Create(self, body, path, typ, id, initial_headers, options=None, **kwargs): # pylint: disable=redefined-builtin - """Creates a Azure Cosmos resource and returns it. + """Creates an Azure Cosmos resource and returns it. :param dict body: :param str path: @@ -602,7 +597,6 @@ async def Create(self, body, path, typ, id, initial_headers, options=None, **kwa :param dict initial_headers: :param dict options: The request options for the request. - :return: The created Azure Cosmos resource. :rtype: @@ -632,7 +626,6 @@ async def UpsertUser(self, database_link, user, options=None, **kwargs): The Azure Cosmos user to upsert. :param dict options: The request options for the request. - :return: The upserted User. :rtype: dict @@ -652,7 +645,6 @@ async def UpsertPermission(self, user_link, permission, options=None, **kwargs): The Azure Cosmos user permission to upsert. :param dict options: The request options for the request. - :return: The upserted permission. :rtype: @@ -674,10 +666,6 @@ async def UpsertItem(self, database_or_container_link, document, options=None, * The Azure Cosmos document to upsert. :param dict options: The request options for the request. - :param bool options['disableAutomaticIdGeneration']: - Disables the automatic id generation. If id is missing in the body and this - option is true, an error will be returned. - :return: The upserted Document. :rtype: @@ -705,7 +693,7 @@ async def UpsertItem(self, database_or_container_link, document, options=None, * return await self.Upsert(document, path, "docs", collection_id, None, options, **kwargs) async def Upsert(self, body, path, typ, id, initial_headers, options=None, **kwargs): # pylint: disable=redefined-builtin - """Upserts a Azure Cosmos resource and returns it. + """Upserts an Azure Cosmos resource and returns it. :param dict body: :param str path: @@ -714,7 +702,6 @@ async def Upsert(self, body, path, typ, id, initial_headers, options=None, **kwa :param dict initial_headers: :param dict options: The request options for the request. - :return: The upserted Azure Cosmos resource. :rtype: @@ -739,16 +726,12 @@ async def Upsert(self, body, path, typ, id, initial_headers, options=None, **kwa async def __Post(self, path, request_params, body, req_headers, **kwargs): """Azure Cosmos 'POST' async http request. - :params str url: - :params str path: - :params (str, unicode, dict) body: - :params dict req_headers: - - :return: - Tuple of (result, headers). - :rtype: - tuple of (dict, dict) - + :param str path: the url to be used for the request. + :param ~azure.cosmos.RequestObject request_params: the request parameters. + :param Union[str, unicode, Dict[Any, Any]] body: the request body. + :param Dict[str, Any] req_headers: the request headers. + :return: Tuple of (result, headers). + :rtype: tuple of (dict, dict) """ request = self.pipeline_client.post(url=path, headers=req_headers) return await asynchronous_request.AsynchronousRequest( @@ -975,17 +958,13 @@ async def Read(self, path, typ, id, initial_headers, options=None, **kwargs): # return result async def __Get(self, path, request_params, req_headers, **kwargs): - """Azure Cosmos 'GET' async async http request. - - :params str url: - :params str path: - :params dict req_headers: - - :return: - Tuple of (result, headers). - :rtype: - tuple of (dict, dict) + """Azure Cosmos 'GET' async http request. + :param str path: the url to be used for the request. + :param ~azure.cosmos.RequestObject request_params: the request parameters. + :param Dict[str, Any] req_headers: the request headers. + :return: Tuple of (result, headers). + :rtype: tuple of (dict, dict) """ request = self.pipeline_client.get(url=path, headers=req_headers) return await asynchronous_request.AsynchronousRequest( @@ -1007,7 +986,6 @@ async def ReplaceUser(self, user_link, user, options=None, **kwargs): :param dict user: :param dict options: The request options for the request. - :return: The new User. :rtype: @@ -1030,7 +1008,6 @@ async def ReplacePermission(self, permission_link, permission, options=None, **k :param dict permission: :param dict options: The request options for the request. - :return: The new Permission. :rtype: @@ -1054,7 +1031,6 @@ async def ReplaceContainer(self, collection_link, collection, options=None, **kw The collection to be used. :param dict options: The request options for the request. - :return: The new Collection. :rtype: @@ -1077,7 +1053,6 @@ async def ReplaceUserDefinedFunction(self, udf_link, udf, options=None, **kwargs :param dict udf: :param dict options: The request options for the request. - :return: The new UDF. :rtype: @@ -1106,7 +1081,6 @@ async def ReplaceTrigger(self, trigger_link, trigger, options=None, **kwargs): :param dict trigger: :param dict options: The request options for the request. - :return: The replaced Trigger. :rtype: @@ -1135,7 +1109,6 @@ async def ReplaceItem(self, document_link, new_document, options=None, **kwargs) :param dict new_document: :param dict options: The request options for the request. - :return: The new Document. :rtype: @@ -1168,7 +1141,6 @@ async def PatchItem(self, document_link, operations, options=None, **kwargs): :param str document_link: The link to the document. :param list operations: The operations for the patch request. :param dict options: The request options for the request. - :return: The new Document. :rtype: @@ -1202,7 +1174,6 @@ async def ReplaceOffer(self, offer_link, offer, **kwargs): :param str offer_link: The link to the offer. :param dict offer: - :return: The replaced Offer. :rtype: @@ -1222,7 +1193,6 @@ async def ReplaceStoredProcedure(self, sproc_link, sproc, options=None, **kwargs :param dict sproc: :param dict options: The request options for the request. - :return: The replaced Stored Procedure. :rtype: @@ -1244,7 +1214,7 @@ async def ReplaceStoredProcedure(self, sproc_link, sproc, options=None, **kwargs return await self.Replace(sproc, path, "sprocs", sproc_id, None, options, **kwargs) async def Replace(self, resource, path, typ, id, initial_headers, options=None, **kwargs): # pylint: disable=redefined-builtin - """Replaces a Azure Cosmos resource and returns it. + """Replaces an Azure Cosmos resource and returns it. :param dict resource: :param str path: @@ -1253,7 +1223,6 @@ async def Replace(self, resource, path, typ, id, initial_headers, options=None, :param dict initial_headers: :param dict options: The request options for the request. - :return: The new Azure Cosmos resource. :rtype: @@ -1276,16 +1245,12 @@ async def Replace(self, resource, path, typ, id, initial_headers, options=None, async def __Put(self, path, request_params, body, req_headers, **kwargs): """Azure Cosmos 'PUT' async http request. - :params str url: - :params str path: - :params (str, unicode, dict) body: - :params dict req_headers: - - :return: - Tuple of (result, headers). - :rtype: - tuple of (dict, dict) - + :param str path: the url to be used for the request. + :param ~azure.cosmos.RequestObject request_params: the request parameters. + :param Union[str, unicode, Dict[Any, Any]] body: the request body. + :param Dict[str, Any] req_headers: the request headers. + :return: Tuple of (result, headers). + :rtype: tuple of (dict, dict) """ request = self.pipeline_client.put(url=path, headers=req_headers) return await asynchronous_request.AsynchronousRequest( @@ -1302,16 +1267,12 @@ async def __Put(self, path, request_params, body, req_headers, **kwargs): async def __Patch(self, path, request_params, request_data, req_headers, **kwargs): """Azure Cosmos 'PATCH' http request. - :params str path: - :params ~azure.cosmos.RequestObject request_params: - :params dict request_data: - :params dict req_headers: - - :return: - Tuple of (result, headers). - :rtype: - tuple of (dict, dict) - + :param str path: the url to be used for the request. + :param ~azure.cosmos.RequestObject request_params: the request parameters. + :param Union[str, unicode, Dict[Any, Any]] request_data: the request body. + :param Dict[str, Any] req_headers: the request headers. + :return: Tuple of (result, headers). + :rtype: tuple of (dict, dict) """ request = self.pipeline_client.patch(url=path, headers=req_headers) return await asynchronous_request.AsynchronousRequest( @@ -1332,7 +1293,6 @@ async def DeleteDatabase(self, database_link, options=None, **kwargs): The link to the database. :param dict options: The request options for the request. - :return: The deleted Database. :rtype: @@ -1353,7 +1313,6 @@ async def DeleteUser(self, user_link, options=None, **kwargs): The link to the user entity. :param dict options: The request options for the request. - :return: The deleted user. :rtype: @@ -1374,7 +1333,6 @@ async def DeletePermission(self, permission_link, options=None, **kwargs): The link to the permission. :param dict options: The request options for the request. - :return: The deleted Permission. :rtype: @@ -1395,7 +1353,6 @@ async def DeleteContainer(self, collection_link, options=None, **kwargs): The link to the document collection. :param dict options: The request options for the request. - :return: The deleted Collection. :rtype: @@ -1416,7 +1373,6 @@ async def DeleteItem(self, document_link, options=None, **kwargs): The link to the document. :param dict options: The request options for the request. - :return: The deleted Document. :rtype: @@ -1437,7 +1393,6 @@ async def DeleteUserDefinedFunction(self, udf_link, options=None, **kwargs): The link to the user-defined function. :param dict options: The request options for the request. - :return: The deleted UDF. :rtype: @@ -1458,7 +1413,6 @@ async def DeleteTrigger(self, trigger_link, options=None, **kwargs): The link to the trigger. :param dict options: The request options for the request. - :return: The deleted Trigger. :rtype: @@ -1479,7 +1433,6 @@ async def DeleteStoredProcedure(self, sproc_link, options=None, **kwargs): The link to the stored procedure. :param dict options: The request options for the request. - :return: The deleted Stored Procedure. :rtype: @@ -1500,7 +1453,6 @@ async def DeleteConflict(self, conflict_link, options=None, **kwargs): The link to the conflict. :param dict options: The request options for the request. - :return: The deleted Conflict. :rtype: @@ -1515,7 +1467,7 @@ async def DeleteConflict(self, conflict_link, options=None, **kwargs): return await self.DeleteResource(path, "conflicts", conflict_id, None, options, **kwargs) async def DeleteResource(self, path, typ, id, initial_headers, options=None, **kwargs): # pylint: disable=redefined-builtin - """Deletes a Azure Cosmos resource and returns it. + """Deletes an Azure Cosmos resource and returns it. :param str path: :param str typ: @@ -1523,7 +1475,6 @@ async def DeleteResource(self, path, typ, id, initial_headers, options=None, **k :param dict initial_headers: :param dict options: The request options for the request. - :return: The deleted Azure Cosmos resource. :rtype: @@ -1547,15 +1498,11 @@ async def DeleteResource(self, path, typ, id, initial_headers, options=None, **k async def __Delete(self, path, request_params, req_headers, **kwargs): """Azure Cosmos 'DELETE' async http request. - :params str url: - :params str path: - :params dict req_headers: - - :return: - Tuple of (result, headers). - :rtype: - tuple of (dict, dict) - + :param str path: the url to be used for the request. + :param ~azure.cosmos.RequestObject request_params: the request parameters. + :param Dict[str, Any] req_headers: the request headers. + :return: Tuple of (result, headers). + :rtype: tuple of (dict, dict) """ request = self.pipeline_client.delete(url=path, headers=req_headers) return await asynchronous_request.AsynchronousRequest( @@ -1575,7 +1522,6 @@ def _ReadPartitionKeyRanges(self, collection_link, feed_options=None, **kwargs): :param str collection_link: The link to the document collection. :param dict feed_options: - :return: Query Iterable of PartitionKeyRanges. :rtype: @@ -1595,7 +1541,6 @@ def _QueryPartitionKeyRanges(self, collection_link, query, options=None, **kwarg :param (str or dict) query: :param dict options: The request options for the request. - :return: Query Iterable of PartitionKeyRanges. :rtype: @@ -1626,7 +1571,6 @@ def ReadDatabases(self, options=None, **kwargs): :param dict options: The request options for the request. - :return: Query Iterable of Databases. :rtype: @@ -1644,7 +1588,6 @@ def QueryDatabases(self, query, options=None, **kwargs): :param (str or dict) query: :param dict options: The request options for the request. - :return: Query Iterable of Databases. :rtype: query_iterable.QueryIterable @@ -1673,7 +1616,6 @@ def ReadContainers(self, database_link, options=None, **kwargs): The link to the database. :param dict options: The request options for the request. - :return: Query Iterable of Collections. :rtype: query_iterable.QueryIterable @@ -1692,7 +1634,6 @@ def QueryContainers(self, database_link, query, options=None, **kwargs): :param (str or dict) query: :param dict options: The request options for the request. - :return: Query Iterable of Collections. :rtype: query_iterable.QueryIterable @@ -1720,14 +1661,12 @@ async def fetch_fn(options): def ReadItems(self, collection_link, feed_options=None, response_hook=None, **kwargs): """Reads all documents in a collection. - :param str collection_link: - The link to the document collection. - :param dict feed_options: - - :return: - Query Iterable of Documents. - :rtype: - query_iterable.QueryIterable + :param str collection_link: The link to the document collection. + :param dict feed_options: The additional options for the operation. + :param response_hook: A callable invoked with the response metadata. + :type response_hook: Callable[[Dict[str, str], Dict[str, Any]] + :return: Query Iterable of Documents. + :rtype: query_iterable.QueryIterable """ if feed_options is None: @@ -1748,14 +1687,11 @@ def QueryItems( :param str database_or_container_link: The link to the database when using partitioning, otherwise link to the document collection. - :param (str or dict) query: - :param dict options: - The request options for the request. - :param str partition_key: - Partition key for the query(default value None) - :param response_hook: - A callable invoked with the response metadata - + :param (str or dict) query: the query to be used + :param dict options: The request options for the request. + :param str partition_key: Partition key for the query(default value None) + :param response_hook: A callable invoked with the response metadata. + :type response_hook: Callable[[Dict[str, str], Dict[str, Any]] :return: Query Iterable of Documents. :rtype: @@ -1808,14 +1744,10 @@ async def fetch_fn(options): def QueryItemsChangeFeed(self, collection_link, options=None, response_hook=None, **kwargs): """Queries documents change feed in a collection. - :param str collection_link: - The link to the document collection. - :param dict options: - The request options for the request. - options may also specify partition key range id. - :param response_hook: - A callable invoked with the response metadata - + :param str collection_link: The link to the document collection. + :param dict options: The request options for the request. + :param response_hook: A callable invoked with the response metadata. + :type response_hook: Callable[[Dict[str, str], Dict[str, Any]] :return: Query Iterable of Documents. :rtype: @@ -1836,17 +1768,12 @@ def _QueryChangeFeed( ): """Queries change feed of a resource in a collection. - :param str collection_link: - The link to the document collection. - :param str resource_type: - The type of the resource. - :param dict options: - The request options for the request. - :param str partition_key_range_id: - Specifies partition key range id. - :param response_hook: - A callable invoked with the response metadata - + :param str collection_link: The link to the document collection. + :param str resource_type: The type of the resource. + :param dict options: The request options for the request. + :param str partition_key_range_id: Specifies partition key range id. + :param response_hook: A callable invoked with the response metadata + :type response_hook: Callable[[Dict[str, str], Dict[str, Any]] :return: Query Iterable of Documents. :rtype: @@ -1899,7 +1826,6 @@ def QueryOffers(self, query, options=None, **kwargs): :param (str or dict) query: :param dict options: The request options for the request - :return: Query Iterable of Offers. :rtype: @@ -1951,7 +1877,6 @@ def QueryUsers(self, database_link, query, options=None, **kwargs): :param (str or dict) query: :param dict options: The request options for the request. - :return: Query Iterable of Users. :rtype: @@ -1984,7 +1909,6 @@ def ReadPermissions(self, user_link, options=None, **kwargs): The link to the user entity. :param dict options: The request options for the request. - :return: Query Iterable of Permissions. :rtype: @@ -2004,7 +1928,6 @@ def QueryPermissions(self, user_link, query, options=None, **kwargs): :param (str or dict) query: :param dict options: The request options for the request. - :return: Query Iterable of Permissions. :rtype: @@ -2036,7 +1959,6 @@ def ReadStoredProcedures(self, collection_link, options=None, **kwargs): The link to the document collection. :param dict options: The request options for the request. - :return: Query Iterable of Stored Procedures. :rtype: @@ -2056,7 +1978,6 @@ def QueryStoredProcedures(self, collection_link, query, options=None, **kwargs): :param (str or dict) query: :param dict options: The request options for the request. - :return: Query Iterable of Stored Procedures. :rtype: @@ -2089,7 +2010,6 @@ def ReadTriggers(self, collection_link, options=None, **kwargs): The link to the document collection. :param dict options: The request options for the request. - :return: Query Iterable of Triggers. :rtype: @@ -2109,7 +2029,6 @@ def QueryTriggers(self, collection_link, query, options=None, **kwargs): :param (str or dict) query: :param dict options: The request options for the request. - :return: Query Iterable of Triggers. :rtype: @@ -2141,7 +2060,6 @@ def ReadUserDefinedFunctions(self, collection_link, options=None, **kwargs): The link to the document collection. :param dict options: The request options for the request. - :return: Query Iterable of UDFs. :rtype: @@ -2161,7 +2079,6 @@ def QueryUserDefinedFunctions(self, collection_link, query, options=None, **kwar :param (str or dict) query: :param dict options: The request options for the request. - :return: Query Iterable of UDFs. :rtype: @@ -2193,7 +2110,6 @@ def ReadConflicts(self, collection_link, feed_options=None, **kwargs): :param str collection_link: The link to the document collection. :param dict feed_options: - :return: Query Iterable of Conflicts. :rtype: @@ -2213,7 +2129,6 @@ def QueryConflicts(self, collection_link, query, options=None, **kwargs): :param (str or dict) query: :param dict options: The request options for the request. - :return: Query Iterable of Conflicts. :rtype: @@ -2242,18 +2157,13 @@ async def fetch_fn(options): async def QueryFeed(self, path, collection_id, query, options, partition_key_range_id=None, **kwargs): """Query Feed for Document Collection resource. - :param str path: - Path to the document collection. - :param str collection_id: - Id of the document collection. + :param str path: Path to the document collection. + :param str collection_id: Id of the document collection. :param (str or dict) query: - :param dict options: - The request options for the request. - :param str partition_key_range_id: - Partition key range id. - :rtype: - tuple - + :param dict options: The request options for the request. + :param str partition_key_range_id: Partition key range id. + :return: Tuple of (result, headers). + :rtype: tuple of (dict, dict) """ return ( await self.__QueryFeed( @@ -2299,12 +2209,9 @@ async def __QueryFeed( :param function response_hook: :param bool is_query_plan: Specifies if the call is to fetch query plan - - :rtype: - list - + :returns: A list of the queried resources. + :rtype: list :raises SystemError: If the query compatibility mode is undefined. - """ if options is None: options = {} @@ -2339,9 +2246,8 @@ def __GetBodiesFromQueryResult(result): initial_headers[http_constants.HttpHeaders.IsQuery] = "true" if ( - self._query_compatibility_mode == CosmosClientConnection._QueryCompatibilityMode.Default - or self._query_compatibility_mode == CosmosClientConnection._QueryCompatibilityMode.Query - ): + self._query_compatibility_mode in (CosmosClientConnection._QueryCompatibilityMode.Default, + CosmosClientConnection._QueryCompatibilityMode.Query)): initial_headers[http_constants.HttpHeaders.ContentType] = runtime_constants.MediaTypes.QueryJson elif self._query_compatibility_mode == CosmosClientConnection._QueryCompatibilityMode.SqlQuery: initial_headers[http_constants.HttpHeaders.ContentType] = runtime_constants.MediaTypes.SQL @@ -2433,9 +2339,8 @@ def __CheckAndUnifyQueryFormat(self, query_body): dict or string """ if ( - self._query_compatibility_mode == CosmosClientConnection._QueryCompatibilityMode.Default - or self._query_compatibility_mode == CosmosClientConnection._QueryCompatibilityMode.Query - ): + self._query_compatibility_mode in (CosmosClientConnection._QueryCompatibilityMode.Default, + CosmosClientConnection._QueryCompatibilityMode.Query)): if not isinstance(query_body, dict) and not isinstance(query_body, str): raise TypeError("query body must be a dict or string.") if isinstance(query_body, dict) and not query_body.get("query"): @@ -2456,13 +2361,9 @@ def _UpdateSessionIfRequired(self, request_headers, response_result, response_he """ Updates session if necessary. - :param dict response_result: - :param dict response_headers: - :param dict response_headers - - :return: - None, but updates the client session if necessary. - + :param dict request_headers: The request headers. + :param dict response_result: The response result. + :param dict response_headers: The response headers. """ # if this request was made with consistency level as session, then update the session @@ -2513,7 +2414,7 @@ def _GetContainerIdWithPathForItem(self, database_or_container_link, document, o collection_id = base.GetResourceIdOrFullNameFromLink(collection_link) return collection_id, document, path - def _GetUserIdWithPathForPermission(self, permission, user_link): # pylint: disable=no-self-use + def _GetUserIdWithPathForPermission(self, permission, user_link): CosmosClientConnection.__ValidateResource(permission) path = base.GetPathFromLink(user_link, "permissions") user_id = base.GetResourceIdOrFullNameFromLink(user_link) @@ -2678,8 +2579,8 @@ def __ValidateResource(resource): if id_[-1] == " ": raise ValueError("Id ends with a space.") - except AttributeError: - raise_with_traceback(TypeError, message="Id type must be a string.") + except AttributeError as e: + raise TypeError("Id type must be a string.") from e async def DeleteAllItemsByPartitionKey( self, diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_database.py b/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_database.py index 93ab39b9548d..e48446d97c48 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_database.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_database.py @@ -161,7 +161,7 @@ async def create_container( :param str id: ID (name) of container to create. :param partition_key: The partition key to use for the container. - :type partition_key: ~azure.cosmos.partition_key.PartitionKey + :type partition_key: ~azure.cosmos.PartitionKey :keyword dict[str, str] indexing_policy: The indexing policy to apply to the container. :keyword int default_ttl: Default time to live (TTL) for items in the container. If unspecified, items do not expire. @@ -255,7 +255,7 @@ async def create_container_if_not_exists( :param str id: ID (name) of container to create. :param partition_key: The partition key to use for the container. - :type partition_key: ~azure.cosmos.partition_key.PartitionKey + :type partition_key: ~azure.cosmos.PartitionKey :keyword dict[str, str] indexing_policy: The indexing policy to apply to the container. :keyword int default_ttl: Default time to live (TTL) for items in the container. If unspecified, items do not expire. @@ -421,7 +421,7 @@ async def replace_container( :class:`ContainerProxy` instance of the container to be replaced. :type container: Union[str, Dict[str, Any], ~azure.cosmos.aio.ContainerProxy] :param partition_key: The partition key to use for the container. - :type partition_key: ~azure.cosmos.partition_key.PartitionKey + :type partition_key: ~azure.cosmos.PartitionKey :keyword dict[str, str] indexing_policy: The indexing policy to apply to the container. :keyword int default_ttl: Default time to live (TTL) for items in the container. If unspecified, items do not expire. @@ -676,7 +676,7 @@ async def replace_user( :keyword response_hook: A callable invoked with the response metadata. :paramtype response_hook: Callable[[Dict[str, str], Dict[str, Any]], None] :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: - If the replace failed or the user with given ID does not exist. + If the replace operation failed or the user with given ID does not exist. :returns: A `UserProxy` instance representing the user after replace went through. :rtype: ~azure.cosmos.aio.UserProxy """ diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_global_endpoint_manager_async.py b/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_global_endpoint_manager_async.py index 1b3a96fd3b59..f59cc37ccaf2 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_global_endpoint_manager_async.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_global_endpoint_manager_async.py @@ -54,7 +54,7 @@ def __init__(self, client): self.refresh_lock = asyncio.Lock() self.last_refresh_time = 0 - def get_refresh_time_interval_in_ms_stub(self): # pylint: disable=no-self-use + def get_refresh_time_interval_in_ms_stub(self): return constants._Constants.DefaultUnavailableLocationExpirationTime def get_write_endpoint(self): @@ -113,6 +113,8 @@ async def _GetDatabaseAccount(self, **kwargs): First tries by using the default endpoint, and if that doesn't work, use the endpoints for the preferred locations in the order they are specified, to get the database account. + :returns: A `DatabaseAccount` instance representing the Cosmos DB Database Account. + :rtype: ~azure.cosmos.DatabaseAccount """ try: database_account = await self._GetDatabaseAccountStub(self.DefaultEndpoint, **kwargs) @@ -135,8 +137,11 @@ async def _GetDatabaseAccount(self, **kwargs): async def _GetDatabaseAccountStub(self, endpoint, **kwargs): """Stub for getting database account from the client. - This can be used for mocking purposes as well. + + :param str endpoint: the endpoint being used to get the database account + :returns: A `DatabaseAccount` instance representing the Cosmos DB Database Account. + :rtype: ~azure.cosmos.DatabaseAccount """ return await self.client.GetDatabaseAccount(endpoint, **kwargs) diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_query_iterable_async.py b/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_query_iterable_async.py index 0752bbf9e4f2..a2d213d1514a 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_query_iterable_async.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_query_iterable_async.py @@ -93,6 +93,7 @@ async def _fetch_next(self, *args): # pylint: disable=unused-argument This method only exists for backward compatibility reasons. (Because QueryIterable has exposed fetch_next_block api). + :param Any args: :return: List of results. :rtype: list """ diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_retry_utility_async.py b/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_retry_utility_async.py index 0d17679b39f0..c22f77a834b2 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_retry_utility_async.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_retry_utility_async.py @@ -51,9 +51,9 @@ async def ExecuteAsync(client, global_endpoint_manager, function, *args, **kwarg Instance of _GlobalEndpointManager class :param function function: Function to be called wrapped with retries - :param (non-keyworded, variable number of arguments list) *args: - :param (keyworded, variable number of arguments list) **kwargs: - + :param list args: + :returns: the result of running the passed in function as a (result, headers) tuple + :rtype: tuple of (dict, dict) """ # instantiate all retry policies here to be applied for each request execution endpointDiscovery_retry_policy = _endpoint_discovery_retry_policy.EndpointDiscoveryRetryPolicy( @@ -76,9 +76,9 @@ async def ExecuteAsync(client, global_endpoint_manager, function, *args, **kwarg ) while True: + client_timeout = kwargs.get('timeout') + start_time = time.time() try: - client_timeout = kwargs.get('timeout') - start_time = time.time() if args: result = await ExecuteFunctionAsync(function, global_endpoint_manager, *args, **kwargs) else: @@ -109,7 +109,7 @@ async def ExecuteAsync(client, global_endpoint_manager, function, *args, **kwarg retry_policy = sessionRetry_policy elif exceptions._partition_range_is_gone(e): retry_policy = partition_key_range_gone_retry_policy - elif e.status_code == StatusCodes.REQUEST_TIMEOUT or e.status_code == StatusCodes.SERVICE_UNAVAILABLE: + elif e.status_code in (StatusCodes.REQUEST_TIMEOUT, e.status_code == StatusCodes.SERVICE_UNAVAILABLE): retry_policy = timeout_failover_retry_policy else: retry_policy = defaultRetry_policy @@ -140,6 +140,10 @@ async def ExecuteAsync(client, global_endpoint_manager, function, *args, **kwarg async def ExecuteFunctionAsync(function, *args, **kwargs): """Stub method so that it can be used for mocking purposes as well. + :param Callable function: the function to execute. + :param list args: the explicit arguments for the function. + :returns: the result of executing the function with the passed in arguments + :rtype: tuple(dict, dict) """ return await function(*args, **kwargs) @@ -170,8 +174,8 @@ async def send(self, request): response = None retry_settings = self.configure_retries(request.context.options) while retry_active: + start_time = time.time() try: - start_time = time.time() _configure_timeout(request, absolute_timeout, per_request_timeout) response = await self.next.send(request) diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_scripts.py b/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_scripts.py index 57f0e39387f6..ec6f14c51d10 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_scripts.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_scripts.py @@ -159,7 +159,7 @@ async def replace_stored_procedure( :param sproc: The ID (name) or dict representing stored procedure to be replaced. :type sproc: Union[str, Dict[str, Any]] :param Dict[str, Any] body: A dict-like object representing the stored procedure to replace. - :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the replace failed or the stored + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the replace operation failed or the stored procedure with given id does not exist. :returns: A dict representing the stored procedure after replace went through. :rtype: Dict[str, Any] @@ -329,8 +329,8 @@ async def replace_trigger( :param trigger: The ID (name) or dict representing trigger to be replaced. :type trigger: Union[str, Dict[str, Any]] :param Dict[str, Any] body: A dict-like object representing the trigger to replace. - :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the replace failed or the trigger with given - id does not exist. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the replace operation failed or the trigger with + given id does not exist. :returns: A dict representing the trigger after replace went through. :rtype: Dict[str, Any] """ @@ -457,8 +457,8 @@ async def replace_user_defined_function( :param udf: The ID (name) or dict representing user-defined function to be replaced. :type udf: Union[str, Dict[str, Any]] :param Dict[str, Any] body: A dict-like object representing the udf to replace. - :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the replace failed or the user-defined function - with the given id does not exist. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the replace operation failed or the user-defined + function with the given id does not exist. :returns: A dict representing the user-defined function after replace went through. :rtype: Dict[str, Any] """ diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_user.py b/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_user.py index 58563f9e1b12..0914ccff5fdd 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_user.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/aio/_user.py @@ -269,9 +269,9 @@ async def replace_permission( :type body: Dict[str, Any] :keyword response_hook: A callable invoked with the response metadata. :paramtype response_hook: Callable[[Dict[str, str], Dict[str, Any]], None] - :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the replace failed or the permission + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the replace operation failed or the permission with given id does not exist. - :returns: A permission object representing the permission after the replace went through. + :returns: A permission object representing the permission after the replace operation went through. :rtype: ~azure.cosmos.Permission """ request_options = build_options(kwargs) diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/auth.py b/sdk/cosmos/azure-cosmos/azure/cosmos/auth.py index cca10023ca5f..754a9c93cdf3 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/auth.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/auth.py @@ -45,10 +45,11 @@ def _get_authorization_header( ): """Gets the authorization header. - :param cosmos_client_connection.CosmosClient cosmos_client: + :param cosmos_client_connection.CosmosClient cosmos_client_connection: :param str verb: :param str path: :param str resource_id_or_fullname: + :param bool is_name_based: :param str resource_type: :param dict headers: :return: The authorization headers. diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/container.py b/sdk/cosmos/azure-cosmos/azure/cosmos/container.py index 3928b0c23999..ddfeabfd8d4e 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/container.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/container.py @@ -135,7 +135,7 @@ def read( range statistics in response headers. :keyword bool populate_quota_info: Enable returning collection storage quota information in response headers. :keyword str session_token: Token for use with Session consistency. - :keyword dict[str,str] initial_headers: Initial headers to be sent as part of the request. + :keyword dict[str, str] initial_headers: Initial headers to be sent as part of the request. :keyword Callable response_hook: A callable invoked with the response metadata. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: Raised if the container couldn't be retrieved. This includes if the container does not exist. @@ -157,15 +157,12 @@ def read( request_options["populatePartitionKeyRangeStatistics"] = populate_partition_key_range_statistics if populate_quota_info is not None: request_options["populateQuotaInfo"] = populate_quota_info - collection_link = self.container_link self._properties = self.client_connection.ReadContainer( collection_link, options=request_options, **kwargs ) - if response_hook: response_hook(self.client_connection.last_response_headers, self._properties) - return cast('Dict[str, Any]', self._properties) @distributed_trace @@ -173,7 +170,7 @@ def read_item( self, item, # type: Union[str, Dict[str, Any]] partition_key, # type: Any - populate_query_metrics=None, # type: Optional[bool] + populate_query_metrics=None, # type: Optional[bool] # pylint:disable=docstring-missing-param post_trigger_include=None, # type: Optional[str] **kwargs # type: Any ): @@ -181,10 +178,12 @@ def read_item( """Get the item identified by `item`. :param item: The ID (name) or dict representing item to retrieve. + :type item: Union[str, Dict[str, Any]] :param partition_key: Partition key for the item to retrieve. - :param post_trigger_include: trigger id to be used as post operation trigger. + :type partition_key: Union[str, int, float, bool] + :param str post_trigger_include: trigger id to be used as post operation trigger. :keyword str session_token: Token for use with Session consistency. - :keyword dict[str,str] initial_headers: Initial headers to be sent as part of the request. + :keyword Dict[str, str] initial_headers: Initial headers to be sent as part of the request. :keyword Callable response_hook: A callable invoked with the response metadata. :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, @@ -192,9 +191,7 @@ def read_item( :returns: Dict representing the item to be retrieved. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The given item couldn't be retrieved. :rtype: dict[str, Any] - .. admonition:: Example: - .. literalinclude:: ../samples/examples.py :start-after: [START update_item] :end-before: [END update_item] @@ -215,6 +212,7 @@ def read_item( UserWarning, ) request_options["populateQueryMetrics"] = populate_query_metrics + if post_trigger_include is not None: request_options["postTriggerInclude"] = post_trigger_include max_integrated_cache_staleness_in_ms = kwargs.pop('max_integrated_cache_staleness_in_ms', None) @@ -231,21 +229,21 @@ def read_item( def read_all_items( self, max_item_count=None, # type: Optional[int] - populate_query_metrics=None, # type: Optional[bool] + populate_query_metrics=None, # type: Optional[bool] # pylint:disable=docstring-missing-param **kwargs # type: Any ): # type: (...) -> Iterable[Dict[str, Any]] """List all the items in the container. - :param max_item_count: Max number of items to be returned in the enumeration operation. + :param int max_item_count: Max number of items to be returned in the enumeration operation. :keyword str session_token: Token for use with Session consistency. - :keyword dict[str,str] initial_headers: Initial headers to be sent as part of the request. + :keyword Dict[str, str] initial_headers: Initial headers to be sent as part of the request. :keyword Callable response_hook: A callable invoked with the response metadata. :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 Iterable of items (dicts). - :rtype: Iterable[dict[str, Any]] + :rtype: Iterable[Dict[str, Any]] """ feed_options = build_options(kwargs) response_hook = kwargs.pop('response_hook', None) @@ -284,13 +282,14 @@ def query_items_change_feed( # type: (...) -> Iterable[Dict[str, Any]] """Get a sorted list of items that were changed, in the order in which they were modified. - :param partition_key_range_id: ChangeFeed requests can be executed against specific partition key ranges. + :param str 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. - :param partition_key: partition key at which ChangeFeed requests are targetted. - :param is_start_from_beginning: Get whether change feed should start from + :param bool 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). - :param continuation: e_tag value to be used as continuation for reading change feed. - :param max_item_count: Max number of items to be returned in the enumeration operation. + :param str continuation: e_tag value to be used as continuation for reading change feed. + :param int max_item_count: Max number of items to be returned in the enumeration operation. + :keyword partition_key: partition key at which ChangeFeed requests are targeted. + :paramtype partition_key: Union[str, int, float, bool] :keyword Callable response_hook: A callable invoked with the response metadata. :returns: An Iterable of items (dicts). :rtype: Iterable[dict[str, Any]] @@ -328,7 +327,7 @@ def query_items( enable_cross_partition_query=None, # type: Optional[bool] max_item_count=None, # type: Optional[int] enable_scan_in_query=None, # type: Optional[bool] - populate_query_metrics=None, # type: Optional[bool] + populate_query_metrics=None, # type: Optional[bool] # pylint:disable=docstring-missing-param **kwargs # type: Any ): # type: (...) -> Iterable[Dict[str, Any]] @@ -339,20 +338,22 @@ def query_items( name is "products," and is aliased as "p" for easier referencing in the WHERE clause. - :param query: The Azure Cosmos DB SQL query to execute. + :param str query: The Azure Cosmos DB SQL query to execute. :param parameters: Optional array of parameters to the query. Each parameter is a dict() with 'name' and 'value' keys. Ignored if no query is provided. - :param partition_key: Specifies the partition key value for the item. - :param enable_cross_partition_query: Allows sending of more than one request to + :type parameters: [List[Dict[str, object]]] + :param partition_key: partition key at which the query request is targeted. + :type partition_key: Union[str, int, float, bool] + :param bool enable_cross_partition_query: Allows sending of more than one request to execute the query in the Azure Cosmos DB service. More than one request is necessary if the query is not scoped to single partition key value. - :param max_item_count: Max number of items to be returned in the enumeration operation. - :param enable_scan_in_query: Allow scan on the queries which couldn't be served as + :param int max_item_count: Max number of items to be returned in the enumeration operation. + :param bool enable_scan_in_query: Allow scan on the queries which couldn't be served as indexing was opted out on the requested paths. - :param populate_query_metrics: Enable returning query metrics in response headers. + :param bool populate_query_metrics: Enable returning query metrics in response headers. :keyword str session_token: Token for use with Session consistency. - :keyword dict[str,str] initial_headers: Initial headers to be sent as part of the request. + :keyword Dict[str, str] initial_headers: Initial headers to be sent as part of the request. :keyword Callable response_hook: A callable invoked with the response metadata. :keyword int continuation_token_limit: **provisional keyword** The size limit in kb of the response continuation token in the query response. Valid values are positive integers. @@ -438,7 +439,7 @@ def replace_item( self, item, # type: Union[str, Dict[str, Any]] body, # type: Dict[str, Any] - populate_query_metrics=None, # type: Optional[bool] + populate_query_metrics=None, # type: Optional[bool] # pylint:disable=docstring-missing-param pre_trigger_include=None, # type: Optional[str] post_trigger_include=None, # type: Optional[str] **kwargs # type: Any @@ -449,19 +450,21 @@ def replace_item( If the item does not already exist in the container, an exception is raised. :param item: The ID (name) or dict representing item to be replaced. + :type item: Union[str, Dict[str, Any]] :param body: A dict-like object representing the item to replace. - :param pre_trigger_include: trigger id to be used as pre operation trigger. - :param post_trigger_include: trigger id to be used as post operation trigger. + :type body: Dict[str, Any] + :param str pre_trigger_include: trigger id to be used as pre operation trigger. + :param str post_trigger_include: trigger id to be used as post operation trigger. :keyword str session_token: Token for use with Session consistency. - :keyword dict[str,str] initial_headers: Initial headers to be sent as part of the request. + :keyword Dict[str, str] initial_headers: Initial headers to be sent as part of the request. :keyword str etag: 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. :keyword ~azure.core.MatchConditions match_condition: The match condition to use upon the etag. :keyword Callable response_hook: A callable invoked with the response metadata. :returns: A dict representing the item after replace went through. - :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The replace failed or the item with + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The replace operation failed or the item with given id does not exist. - :rtype: dict[str, Any] + :rtype: Dict[str, Any] """ item_link = self._get_document_link(item) request_options = build_options(kwargs) @@ -489,7 +492,7 @@ def replace_item( def upsert_item( self, body, # type: Dict[str, Any] - populate_query_metrics=None, # type: Optional[bool] + populate_query_metrics=None, # type: Optional[bool] # pylint:disable=docstring-missing-param pre_trigger_include=None, # type: Optional[str] post_trigger_include=None, # type: Optional[str] **kwargs # type: Any @@ -501,17 +504,18 @@ def upsert_item( does not already exist, it is inserted. :param body: A dict-like object representing the item to update or insert. - :param pre_trigger_include: trigger id to be used as pre operation trigger. - :param post_trigger_include: trigger id to be used as post operation trigger. + :type body: Dict[str, Any] + :param str pre_trigger_include: trigger id to be used as pre operation trigger. + :param str post_trigger_include: trigger id to be used as post operation trigger. :keyword str session_token: Token for use with Session consistency. - :keyword dict[str,str] initial_headers: Initial headers to be sent as part of the request. + :keyword Dict[str, str] initial_headers: Initial headers to be sent as part of the request. :keyword str etag: 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. :keyword ~azure.core.MatchConditions match_condition: The match condition to use upon the etag. :keyword Callable response_hook: A callable invoked with the response metadata. :returns: A dict representing the upserted item. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The given item could not be upserted. - :rtype: dict[str, Any] + :rtype: Dict[str, Any] """ request_options = build_options(kwargs) response_hook = kwargs.pop('response_hook', None) @@ -541,10 +545,10 @@ def upsert_item( def create_item( self, body, # type: Dict[str, Any] - populate_query_metrics=None, # type: Optional[bool] + populate_query_metrics=None, # type: Optional[bool] # pylint:disable=docstring-missing-param pre_trigger_include=None, # type: Optional[str] post_trigger_include=None, # type: Optional[str] - indexing_directive=None, # type: Optional[Any] + indexing_directive=None, # type: Optional[Union[int, ~azure.cosmos.documents.IndexingDirective]] **kwargs # type: Any ): # type: (...) -> Dict[str, Any] @@ -554,19 +558,22 @@ def create_item( :func:`ContainerProxy.upsert_item` method. :param body: A dict-like object representing the item to create. - :param pre_trigger_include: trigger id to be used as pre operation trigger. - :param post_trigger_include: trigger id to be used as post operation trigger. - :param indexing_directive: Indicate whether the document should be omitted from indexing. + :type body: Dict[str, Any] + :param str pre_trigger_include: trigger id to be used as pre operation trigger. + :param str post_trigger_include: trigger id to be used as post operation trigger. + :param indexing_directive: Enumerates the possible values to indicate whether the document should + be omitted from indexing. Possible values include: 0 for Default, 1 for Exclude, or 2 for Include. + :type indexing_directive: Union[int, ~azure.cosmos.documents.IndexingDirective] :keyword bool enable_automatic_id_generation: Enable automatic id generation if no id present. :keyword str session_token: Token for use with Session consistency. - :keyword dict[str,str] initial_headers: Initial headers to be sent as part of the request. + :keyword Dict[str, str] initial_headers: Initial headers to be sent as part of the request. :keyword str etag: 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. :keyword ~azure.core.MatchConditions match_condition: The match condition to use upon the etag. :keyword Callable response_hook: A callable invoked with the response metadata. :returns: A dict representing the new item. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: Item with the given ID already exists. - :rtype: dict[str, Any] + :rtype: Dict[str, Any] """ request_options = build_options(kwargs) response_hook = kwargs.pop('response_hook', None) @@ -600,7 +607,7 @@ def patch_item( patch_operations: List[Dict[str, Any]], **kwargs: Any ) -> Dict[str, Any]: - """ **Provisional method** Patches the specified item with the provided operations if it + """ Patches the specified item with the provided operations if it exists in the container. If the item does not already exist in the container, an exception is raised. @@ -643,8 +650,8 @@ def patch_item( def delete_item( self, item, # type: Union[Dict[str, Any], str] - partition_key, # type: Any - populate_query_metrics=None, # type: Optional[bool] + partition_key, # type: Union[str, int, float, bool] + populate_query_metrics=None, # type: Optional[bool] # pylint:disable=docstring-missing-param pre_trigger_include=None, # type: Optional[str] post_trigger_include=None, # type: Optional[str] **kwargs # type: Any @@ -655,11 +662,13 @@ def delete_item( If the item does not already exist in the container, an exception is raised. :param item: The ID (name) or dict representing item to be deleted. + :type item: Union[str, Dict[str, Any]] :param partition_key: Specifies the partition key value for the item. - :param pre_trigger_include: trigger id to be used as pre operation trigger. - :param post_trigger_include: trigger id to be used as post operation trigger. + :type partition_key: Union[str, int, float, bool] + :param str pre_trigger_include: trigger id to be used as pre operation trigger. + :param str post_trigger_include: trigger id to be used as post operation trigger. :keyword str session_token: Token for use with Session consistency. - :keyword dict[str,str] initial_headers: Initial headers to be sent as part of the request. + :keyword Dict[str, str] initial_headers: Initial headers to be sent as part of the request. :keyword str etag: 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. :keyword ~azure.core.MatchConditions match_condition: The match condition to use upon the etag. @@ -693,6 +702,7 @@ def read_offer(self, **kwargs): # type: (Any) -> Offer """Get the ThroughputProperties object for this container. If no ThroughputProperties already exist for the container, an exception is raised. + :keyword Callable response_hook: A callable invoked with the response metadata. :returns: Throughput for the container. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: No throughput properties exists for the container or @@ -711,6 +721,7 @@ def get_throughput(self, **kwargs): """Get the ThroughputProperties object for this container. If no ThroughputProperties already exist for the container, an exception is raised. + :keyword Callable response_hook: A callable invoked with the response metadata. :returns: Throughput for the container. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: No throughput properties exists for the container or @@ -742,7 +753,8 @@ def replace_throughput(self, throughput, **kwargs): If no ThroughputProperties already exist for the container, an exception is raised. - :param throughput: The throughput to be set (an integer). + :param throughput: The throughput to be set. + :type throughput: Union[int, ThroughputProperties] :keyword Callable response_hook: A callable invoked with the response metadata. :returns: ThroughputProperties for the container, updated with new throughput. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: No throughput properties exist for the container @@ -776,7 +788,7 @@ def list_conflicts(self, max_item_count=None, **kwargs): # type: (Optional[int], Any) -> Iterable[Dict[str, Any]] """List all the conflicts in the container. - :param max_item_count: Max number of items to be returned in the enumeration operation. + :param int max_item_count: Max number of items to be returned in the enumeration operation. :keyword Callable response_hook: A callable invoked with the response metadata. :returns: An Iterable of conflicts (dicts). :rtype: Iterable[dict[str, Any]] @@ -797,25 +809,27 @@ def list_conflicts(self, max_item_count=None, **kwargs): def query_conflicts( self, query, # type: str - parameters=None, # type: Optional[List[str]] + parameters=None, # type: Optional[List[Dict[str, object]]] enable_cross_partition_query=None, # type: Optional[bool] - partition_key=None, # type: Optional[Any] + partition_key=None, # type: Optional[Union[str, int, float, bool]] max_item_count=None, # type: Optional[int] **kwargs # type: Any ): # type: (...) -> Iterable[Dict[str, Any]] """Return all conflicts matching a given `query`. - :param query: The Azure Cosmos DB SQL query to execute. + :param str query: The Azure Cosmos DB SQL query to execute. :param parameters: Optional array of parameters to the query. Ignored if no query is provided. - :param enable_cross_partition_query: Allows sending of more than one request to execute + :type parameters: List[Dict[str, object]] + :param bool enable_cross_partition_query: Allows sending of more than one request to execute the query in the Azure Cosmos DB service. More than one request is necessary if the query is not scoped to single partition key value. :param partition_key: Specifies the partition key value for the item. - :param max_item_count: Max number of items to be returned in the enumeration operation. + :type partition_key: Union[str, int, float, bool] + :param int max_item_count: Max number of items to be returned in the enumeration operation. :keyword Callable response_hook: A callable invoked with the response metadata. :returns: An Iterable of conflicts (dicts). - :rtype: Iterable[dict[str, Any]] + :rtype: Iterable[Dict[str, Any]] """ feed_options = build_options(kwargs) response_hook = kwargs.pop('response_hook', None) @@ -838,15 +852,17 @@ def query_conflicts( @distributed_trace def get_conflict(self, conflict, partition_key, **kwargs): - # type: (Union[str, Dict[str, Any]], Any, Any) -> Dict[str, Any] + # type: (Union[str, Dict[str, Any]], Union[str, int, float, bool], Any) -> Dict[str, Any] """Get the conflict identified by `conflict`. :param conflict: The ID (name) or dict representing the conflict to retrieve. + :type conflict: Union[str, Dict[str, Any]] :param partition_key: Partition key for the conflict to retrieve. + :type partition_key: Union[str, int, float, bool] :keyword Callable response_hook: A callable invoked with the response metadata. :returns: A dict representing the retrieved conflict. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The given conflict couldn't be retrieved. - :rtype: dict[str, Any] + :rtype: Dict[str, Any] """ request_options = build_options(kwargs) response_hook = kwargs.pop('response_hook', None) @@ -862,13 +878,15 @@ def get_conflict(self, conflict, partition_key, **kwargs): @distributed_trace def delete_conflict(self, conflict, partition_key, **kwargs): - # type: (Union[str, Dict[str, Any]], Any, Any) -> None + # type: (Union[str, Dict[str, Any]], Union[str, int, float, bool], Any) -> None """Delete a specified conflict from the container. If the conflict does not already exist in the container, an exception is raised. :param conflict: The ID (name) or dict representing the conflict to be deleted. + :type conflict: Union[str, Dict[str, Any]] :param partition_key: Partition key for the conflict to delete. + :type partition_key: Union[str, int, float, bool] :keyword Callable response_hook: A callable invoked with the response metadata. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The conflict wasn't deleted successfully. :raises ~azure.cosmos.exceptions.CosmosResourceNotFoundError: The conflict does not exist in the container. @@ -898,7 +916,7 @@ def delete_all_items_by_partition_key( this background task. :param partition_key: Partition key for the items to be deleted. - :type partition_key: Any + :type partition_key: Union[str, int, float, bool] :keyword str pre_trigger_include: trigger id to be used as pre operation trigger. :keyword str post_trigger_include: trigger id to be used as post operation trigger. :keyword str session_token: Token for use with Session consistency. diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/cosmos_client.py b/sdk/cosmos/azure-cosmos/azure/cosmos/cosmos_client.py index 4e45166d665e..a2904fe5dcf7 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/cosmos_client.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/cosmos_client.py @@ -135,7 +135,7 @@ class CosmosClient(object): # pylint: disable=client-accepts-api-version-keywor Use this client to configure and execute requests to the Azure Cosmos DB service. - Its recommended to maintain a single instance of CosmosClient per lifetime of the application which enables + It's recommended to maintain a single instance of CosmosClient per lifetime of the application which enables efficient connection management and performance. CosmosClient initialization is a heavy operation - don't use initialization CosmosClient instances as @@ -213,9 +213,11 @@ def from_connection_string(cls, conn_str, credential=None, consistency_level=Non :param str conn_str: The connection string. :param credential: Alternative credentials to use instead of the key provided in the connection string. - :type credential: str or dict(str, str) - :param Optional[str] consistency_level: + :type credential: Union[str, Dict[str, str]] + :param str consistency_level: Consistency level to use for the session. The default value is None (Account level). + :returns: A CosmosClient instance representing the new client. + :rtype: ~azure.cosmos.CosmosClient """ settings = _parse_connection_str(conn_str, credential) return cls( @@ -241,7 +243,7 @@ def _get_database_link(database_or_id): def create_database( # pylint: disable=redefined-builtin self, id, # type: str - populate_query_metrics=None, # type: Optional[bool] + populate_query_metrics=None, # type: Optional[bool] # pylint:disable=docstring-missing-param offer_throughput=None, # type: Optional[Union[int, ThroughputProperties]] **kwargs # type: Any ): @@ -249,11 +251,11 @@ def create_database( # pylint: disable=redefined-builtin """ Create a new database with the given ID (name). - :param id: ID (name) of the database to create. + :param str id: ID (name) of the database to create. :param offer_throughput: The provisioned throughput for this offer. - :paramtype offer_throughput: int or ~azure.cosmos.ThroughputProperties. + :type offer_throughput: Union[int, ~azure.cosmos.ThroughputProperties] :keyword str session_token: Token for use with Session consistency. - :keyword dict[str,str] initial_headers: Initial headers to be sent as part of the request. + :keyword Dict[str, str] initial_headers: Initial headers to be sent as part of the request. :keyword str etag: 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. :keyword ~azure.core.MatchConditions match_condition: The match condition to use upon the etag. @@ -261,9 +263,7 @@ def create_database( # pylint: disable=redefined-builtin :returns: A DatabaseProxy instance representing the new database. :rtype: ~azure.cosmos.DatabaseProxy :raises ~azure.cosmos.exceptions.CosmosResourceExistsError: Database with the given ID already exists. - .. admonition:: Example: - .. literalinclude:: ../samples/examples.py :start-after: [START create_database] :end-before: [END create_database] @@ -292,26 +292,24 @@ def create_database( # pylint: disable=redefined-builtin def create_database_if_not_exists( # pylint: disable=redefined-builtin self, id, # type: str - populate_query_metrics=None, # type: Optional[bool] + populate_query_metrics=None, # type: Optional[bool] # pylint:disable=docstring-missing-param offer_throughput=None, # type: Optional[Union[int, ThroughputProperties]] **kwargs # type: Any ): # type: (...) -> DatabaseProxy """ 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. - :param id: ID (name) of the database to read or create. + :param str id: ID (name) of the database to read or create. :param bool populate_query_metrics: Enable returning query metrics in response headers. :param offer_throughput: The provisioned throughput for this offer. - :type offer_throughput: int or ~azure.cosmos.ThroughputProperties. + :type offer_throughput: Union[int, ~azure.cosmos.ThroughputProperties] :keyword str session_token: Token for use with Session consistency. - :keyword dict[str,str] initial_headers: Initial headers to be sent as part of the request. + :keyword Dict[str, str] initial_headers: Initial headers to be sent as part of the request. :keyword str etag: 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. :keyword ~azure.core.MatchConditions match_condition: The match condition to use upon the etag. @@ -359,7 +357,7 @@ def get_database_client(self, database): def list_databases( self, max_item_count=None, # type: Optional[int] - populate_query_metrics=None, # type: Optional[bool] + populate_query_metrics=None, # type: Optional[bool] # pylint:disable=docstring-missing-param **kwargs # type: Any ): # type: (...) -> Iterable[Dict[str, Any]] @@ -367,10 +365,10 @@ def list_databases( :param int max_item_count: Max number of items to be returned in the enumeration operation. :keyword str session_token: Token for use with Session consistency. - :keyword dict[str,str] initial_headers: Initial headers to be sent as part of the request. + :keyword Dict[str, str] initial_headers: Initial headers to be sent as part of the request. :keyword Callable response_hook: A callable invoked with the response metadata. :returns: An Iterable of database properties (dicts). - :rtype: Iterable[dict[str, str]] + :rtype: Iterable[Dict[str, str]] """ feed_options = build_options(kwargs) response_hook = kwargs.pop('response_hook', None) @@ -395,7 +393,7 @@ def query_databases( parameters=None, # type: Optional[List[Dict[str, Any]]] enable_cross_partition_query=None, # type: Optional[bool] max_item_count=None, # type: Optional[int] - populate_query_metrics=None, # type: Optional[bool] + populate_query_metrics=None, # type: Optional[bool] # pylint:disable=docstring-missing-param **kwargs # type: Any ): # type: (...) -> Iterable[Dict[str, Any]] @@ -407,10 +405,10 @@ def query_databases( served as indexing was opted out on the requested paths. :param int max_item_count: Max number of items to be returned in the enumeration operation. :keyword str session_token: Token for use with Session consistency. - :keyword dict[str,str] initial_headers: Initial headers to be sent as part of the request. + :keyword Dict[str, str] initial_headers: Initial headers to be sent as part of the request. :keyword Callable response_hook: A callable invoked with the response metadata. :returns: An Iterable of database properties (dicts). - :rtype: Iterable[dict[str, str]] + :rtype: Iterable[Dict[str, str]] """ feed_options = build_options(kwargs) response_hook = kwargs.pop('response_hook', None) @@ -443,7 +441,7 @@ def query_databases( def delete_database( self, database, # type: Union[str, DatabaseProxy, Dict[str, Any]] - populate_query_metrics=None, # type: Optional[bool] + populate_query_metrics=None, # type: Optional[bool] # pylint:disable=docstring-missing-param **kwargs # type: Any ): # type: (...) -> None @@ -451,9 +449,9 @@ def delete_database( :param database: The ID (name), dict representing the properties or :class:`DatabaseProxy` instance of the database to delete. - :type database: str or dict(str, str) or ~azure.cosmos.DatabaseProxy + :type database: Union[str, Dict[str, str], ~azure.cosmos.DatabaseProxy] :keyword str session_token: Token for use with Session consistency. - :keyword dict[str,str] initial_headers: Initial headers to be sent as part of the request. + :keyword Dict[str, str] initial_headers: Initial headers to be sent as part of the request. :keyword str etag: 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. :keyword ~azure.core.MatchConditions match_condition: The match condition to use upon the etag. diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/database.py b/sdk/cosmos/azure-cosmos/azure/cosmos/database.py index 874d9face6d5..18135dacf689 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/database.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/database.py @@ -38,6 +38,7 @@ __all__ = ("DatabaseProxy",) + # pylint: disable=protected-access # pylint: disable=missing-client-constructor-parameter-credential,missing-client-constructor-parameter-kwargs @@ -115,7 +116,9 @@ def _get_properties(self): return self._properties @distributed_trace - def read(self, populate_query_metrics=None, **kwargs): + def read(self, + populate_query_metrics=None, # pylint:disable=docstring-missing-param + **kwargs): # type: (Optional[bool], Any) -> Dict[str, Any] """Read the database properties. @@ -151,10 +154,10 @@ def read(self, populate_query_metrics=None, **kwargs): def create_container( self, id, # type: str # pylint: disable=redefined-builtin - partition_key, # type: Any + partition_key, # type: ~azure.cosmos.PartitionKey indexing_policy=None, # type: Optional[Dict[str, Any]] default_ttl=None, # type: Optional[int] - populate_query_metrics=None, # type: Optional[bool] + populate_query_metrics=None, # type: Optional[bool] # pylint:disable=docstring-missing-param offer_throughput=None, # type: Optional[Union[int, ThroughputProperties]] unique_key_policy=None, # type: Optional[Dict[str, Any]] conflict_resolution_policy=None, # type: Optional[Dict[str, Any]] @@ -165,16 +168,16 @@ def create_container( If a container with the given ID already exists, a CosmosResourceExistsError is raised. - :param id: ID (name) of container to create. - :param partition_key: The partition key to use for the container. - :param indexing_policy: The indexing policy to apply to the container. - :param default_ttl: Default time to live (TTL) for items in the container. If unspecified, items do not expire. + :param str id: ID (name) of container to create. + :param ~azure.cosmos.PartitionKey partition_key: The partition key to use for the container. + :param Dict[str, Any] indexing_policy: The indexing policy to apply to the container. + :param int default_ttl: Default time to live (TTL) for items in the container. If unused, items do not expire. :param offer_throughput: The provisioned throughput for this offer. - :type offer_throughput: int or ~azure.cosmos.ThroughputProperties. - :param unique_key_policy: The unique key policy to apply to the container. - :param conflict_resolution_policy: The conflict resolution policy to apply to the container. + :type offer_throughput: Union[int, ~azure.cosmos.ThroughputProperties] + :param Dict[str, Any] unique_key_policy: The unique key policy to apply to the container. + :param Dict[str, Any] conflict_resolution_policy: The conflict resolution policy to apply to the container. :keyword str session_token: Token for use with Session consistency. - :keyword dict[str,str] initial_headers: Initial headers to be sent as part of the request. + :keyword Dict[str, str] initial_headers: Initial headers to be sent as part of the request. :keyword str etag: 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. :keyword ~azure.core.MatchConditions match_condition: The match condition to use upon the etag. @@ -185,9 +188,7 @@ def create_container( :returns: A `ContainerProxy` instance representing the new container. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The container creation failed. :rtype: ~azure.cosmos.ContainerProxy - .. admonition:: Example: - .. literalinclude:: ../samples/examples.py :start-after: [START create_container] :end-before: [END create_container] @@ -195,7 +196,6 @@ def create_container( :dedent: 0 :caption: Create a container with default settings: :name: create_container - .. literalinclude:: ../samples/examples.py :start-after: [START create_container_with_settings] :end-before: [END create_container_with_settings] @@ -220,7 +220,6 @@ def create_container( definition["uniqueKeyPolicy"] = unique_key_policy if conflict_resolution_policy is not None: definition["conflictResolutionPolicy"] = conflict_resolution_policy - analytical_storage_ttl = kwargs.pop("analytical_storage_ttl", None) if analytical_storage_ttl is not None: definition["analyticalStorageTtl"] = analytical_storage_ttl @@ -250,7 +249,7 @@ def create_container_if_not_exists( partition_key, # type: Any indexing_policy=None, # type: Optional[Dict[str, Any]] default_ttl=None, # type: Optional[int] - populate_query_metrics=None, # type: Optional[bool] + populate_query_metrics=None, # type: Optional[bool] # pylint:disable=docstring-missing-param offer_throughput=None, # type: Optional[Union[int, ThroughputProperties]] unique_key_policy=None, # type: Optional[Dict[str, Any]] conflict_resolution_policy=None, # type: Optional[Dict[str, Any]] @@ -267,13 +266,12 @@ def create_container_if_not_exists( :param partition_key: The partition key to use for the container. :param indexing_policy: The indexing policy to apply to the container. :param default_ttl: Default time to live (TTL) for items in the container. If unspecified, items do not expire. - :param populate_query_metrics: Enable returning query metrics in response headers. :param offer_throughput: The provisioned throughput for this offer. :paramtype offer_throughput: int or ~azure.cosmos.ThroughputProperties. :param unique_key_policy: The unique key policy to apply to the container. :param conflict_resolution_policy: The conflict resolution policy to apply to the container. :keyword str session_token: Token for use with Session consistency. - :keyword dict[str,str] initial_headers: Initial headers to be sent as part of the request. + :keyword Dict[str, str] initial_headers: Initial headers to be sent as part of the request. :keyword str etag: 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. :keyword ~azure.core.MatchConditions match_condition: The match condition to use upon the etag. @@ -285,7 +283,6 @@ def create_container_if_not_exists( :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The container read or creation failed. :rtype: ~azure.cosmos.ContainerProxy """ - analytical_storage_ttl = kwargs.pop("analytical_storage_ttl", None) try: container_proxy = self.get_container_client(id) @@ -311,7 +308,7 @@ def create_container_if_not_exists( def delete_container( self, container, # type: Union[str, ContainerProxy, Dict[str, Any]] - populate_query_metrics=None, # type: Optional[bool] + populate_query_metrics=None, # type: Optional[bool] # pylint:disable=docstring-missing-param **kwargs # type: Any ): # type: (...) -> None @@ -320,8 +317,9 @@ def delete_container( :param container: The ID (name) of the container to delete. You can either pass in the ID of the container to delete, a :class:`ContainerProxy` instance or a dict representing the properties of the container. + :type container: Union[str, ContainerProxy, Dict[str, Any]] :keyword str session_token: Token for use with Session consistency. - :keyword dict[str,str] initial_headers: Initial headers to be sent as part of the request. + :keyword Dict[str, str] initial_headers: Initial headers to be sent as part of the request. :keyword str etag: 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. :keyword ~azure.core.MatchConditions match_condition: The match condition to use upon the etag. @@ -349,6 +347,7 @@ def get_container_client(self, container): :param container: The ID (name) of the container, a :class:`ContainerProxy` instance, or a dict representing the properties of the container to be retrieved. + :type container: Union[str, ContainerProxy, Dict[str, Any]] :returns: A `ContainerProxy` instance representing the retrieved database. :rtype: ~azure.cosmos.ContainerProxy @@ -373,16 +372,19 @@ def get_container_client(self, container): return ContainerProxy(self.client_connection, self.database_link, id_value) @distributed_trace - def list_containers(self, max_item_count=None, populate_query_metrics=None, **kwargs): + def list_containers(self, + max_item_count=None, + populate_query_metrics=None, # pylint:disable=docstring-missing-param + **kwargs): # type: (Optional[int], Optional[bool], Any) -> Iterable[Dict[str, Any]] """List the containers in the database. - :param max_item_count: Max number of items to be returned in the enumeration operation. + :param int max_item_count: Max number of items to be returned in the enumeration operation. :keyword str session_token: Token for use with Session consistency. - :keyword dict[str,str] initial_headers: Initial headers to be sent as part of the request. + :keyword Dict[str, str] initial_headers: Initial headers to be sent as part of the request. :keyword Callable response_hook: A callable invoked with the response metadata. :returns: An Iterable of container properties (dicts). - :rtype: Iterable[dict[str, Any]] + :rtype: Iterable[Dict[str, Any]] .. admonition:: Example: @@ -416,22 +418,23 @@ def list_containers(self, max_item_count=None, populate_query_metrics=None, **kw def query_containers( self, query=None, # type: Optional[str] - parameters=None, # type: Optional[List[str]] + parameters=None, # type: Optional[List[Dict[str, Any]]] max_item_count=None, # type: Optional[int] - populate_query_metrics=None, # type: Optional[bool] + populate_query_metrics=None, # type: Optional[bool] # pylint:disable=docstring-missing-param **kwargs # type: Any ): # type: (...) -> Iterable[Dict[str, Any]] """List the properties for containers in the current database. - :param query: The Azure Cosmos DB SQL query to execute. + :param str query: The Azure Cosmos DB SQL query to execute. :param parameters: Optional array of parameters to the query. Ignored if no query is provided. - :param max_item_count: Max number of items to be returned in the enumeration operation. + :type parameters: List[Dict[str, Any]] + :param int max_item_count: Max number of items to be returned in the enumeration operation. :keyword str session_token: Token for use with Session consistency. - :keyword dict[str,str] initial_headers: Initial headers to be sent as part of the request. + :keyword Dict[str, str] initial_headers: Initial headers to be sent as part of the request. :keyword Callable response_hook: A callable invoked with the response metadata. :returns: An Iterable of container properties (dicts). - :rtype: Iterable[dict[str, Any]] + :rtype: Iterable[Dict[str, Any]] """ feed_options = build_options(kwargs) response_hook = kwargs.pop('response_hook', None) @@ -462,7 +465,7 @@ def replace_container( indexing_policy=None, # type: Optional[Dict[str, Any]] default_ttl=None, # type: Optional[int] conflict_resolution_policy=None, # type: Optional[Dict[str, Any]] - populate_query_metrics=None, # type: Optional[bool] + populate_query_metrics=None, # type: Optional[bool] # pylint:disable=docstring-missing-param **kwargs # type: Any ): # type: (...) -> ContainerProxy @@ -473,17 +476,18 @@ def replace_container( :param container: The ID (name), dict representing the properties or :class:`ContainerProxy` instance of the container to be replaced. - :param partition_key: The partition key to use for the container. - :param indexing_policy: The indexing policy to apply to the container. - :param default_ttl: Default time to live (TTL) for items in the container. + :type container: Union[str, ContainerProxy, Dict[str, Any]] + :param ~azure.cosmos.PartitionKey partition_key: The partition key to use for the container. + :param Dict[str, Any] indexing_policy: The indexing policy to apply to the container. + :param int default_ttl: Default time to live (TTL) for items in the container. If unspecified, items do not expire. - :param conflict_resolution_policy: The conflict resolution policy to apply to the container. + :param Dict[str, Any] conflict_resolution_policy: The conflict resolution policy to apply to the container. :param populate_query_metrics: Enable returning query metrics in response headers. :keyword str session_token: Token for use with Session consistency. :keyword str etag: 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. :keyword ~azure.core.MatchConditions match_condition: The match condition to use upon the etag. - :keyword dict[str,str] initial_headers: Initial headers to be sent as part of the request. + :keyword Dict[str, str] initial_headers: Initial headers to be sent as part of the request. :keyword Callable response_hook: A callable invoked with the response metadata. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: Raised if the container couldn't be replaced. This includes if the container with given id does not exist. @@ -492,9 +496,7 @@ def replace_container( note that analytical storage can only be enabled on Synapse Link enabled accounts. :returns: A `ContainerProxy` instance representing the container after replace completed. :rtype: ~azure.cosmos.ContainerProxy - .. admonition:: Example: - .. literalinclude:: ../samples/examples.py :start-after: [START reset_container_properties] :end-before: [END reset_container_properties] @@ -544,10 +546,10 @@ def list_users(self, max_item_count=None, **kwargs): # type: (Optional[int], Any) -> Iterable[Dict[str, Any]] """List all the users in the container. - :param max_item_count: Max number of users to be returned in the enumeration operation. + :param int max_item_count: Max number of users to be returned in the enumeration operation. :keyword Callable response_hook: A callable invoked with the response metadata. :returns: An Iterable of user properties (dicts). - :rtype: Iterable[dict[str, Any]] + :rtype: Iterable[Dict[str, Any]] """ feed_options = build_options(kwargs) response_hook = kwargs.pop('response_hook', None) @@ -566,12 +568,13 @@ def query_users(self, query, parameters=None, max_item_count=None, **kwargs): # type: (str, Optional[List[str]], Optional[int], Any) -> Iterable[Dict[str, Any]] """Return all users matching the given `query`. - :param query: The Azure Cosmos DB SQL query to execute. + :param str query: The Azure Cosmos DB SQL query to execute. :param parameters: Optional array of parameters to the query. Ignored if no query is provided. - :param max_item_count: Max number of users to be returned in the enumeration operation. + :type parameters: Dict[str, Any] + :param int max_item_count: Max number of users to be returned in the enumeration operation. :keyword Callable response_hook: A callable invoked with the response metadata. :returns: An Iterable of user properties (dicts). - :rtype: Iterable[str, Any] + :rtype: Iterable[Dict[str, Any]] """ feed_options = build_options(kwargs) response_hook = kwargs.pop('response_hook', None) @@ -594,6 +597,7 @@ def get_user_client(self, user): :param user: The ID (name), dict representing the properties or :class:`UserProxy` instance of the user to be retrieved. + :type user: Union[str, UserProxy, Dict[str, Any]] :returns: A `UserProxy` instance representing the retrieved user. :rtype: ~azure.cosmos.UserProxy """ @@ -615,7 +619,7 @@ def create_user(self, body, **kwargs): To update or replace an existing user, use the :func:`ContainerProxy.upsert_user` method. - :param body: A dict-like object with an `id` key and value representing the user to be created. + :param Dict[str, Any] 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 Callable response_hook: A callable invoked with the response metadata. :returns: A `UserProxy` instance representing the new user. @@ -653,7 +657,7 @@ def upsert_user(self, body, **kwargs): If the user already exists in the container, it is replaced. If the user does not already exist, it is inserted. - :param body: A dict-like object representing the user to update or insert. + :param Dict[str, Any] body: A dict-like object representing the user to update or insert. :keyword Callable response_hook: A callable invoked with the response metadata. :returns: A `UserProxy` instance representing the upserted user. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the given user could not be upserted. @@ -675,21 +679,22 @@ def upsert_user(self, body, **kwargs): @distributed_trace def replace_user( - self, - user, # type: Union[str, UserProxy, Dict[str, Any]] - body, # type: Dict[str, Any] - **kwargs # type: Any + self, + user, # type: Union[str, UserProxy, Dict[str, Any]] + body, # type: Dict[str, Any] + **kwargs # type: Any ): # type: (...) -> UserProxy """Replaces the specified user if it exists in the container. :param user: The ID (name), dict representing the properties or :class:`UserProxy` instance of the user to be replaced. - :param body: A dict-like object representing the user to replace. + :type user: Union[str, UserProxy, Dict[str, Any]] + :param Dict[str, Any] body: A dict-like object representing the user to replace. :keyword Callable response_hook: A callable invoked with the response metadata. :returns: A `UserProxy` instance representing the user after replace went through. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: - If the replace failed or the user with given ID does not exist. + If the replace operation failed or the user with given ID does not exist. :rtype: ~azure.cosmos.UserProxy """ request_options = build_options(kwargs) @@ -716,6 +721,7 @@ def delete_user(self, user, **kwargs): :param user: The ID (name), dict representing the properties or :class:`UserProxy` instance of the user to be deleted. + :type user: Union[str, UserProxy, Dict[str, Any]] :keyword Callable response_hook: A callable invoked with the response metadata. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The user wasn't deleted successfully. :raises ~azure.cosmos.exceptions.CosmosResourceNotFoundError: The user does not exist in the container. @@ -734,7 +740,9 @@ def delete_user(self, user, **kwargs): def read_offer(self, **kwargs): # type: (Any) -> ThroughputProperties """Get the ThroughputProperties object for this database. + If no ThroughputProperties already exist for the database, an exception is raised. + :keyword Callable response_hook: A callable invoked with the response metadata. :returns: ThroughputProperties for the database. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: No throughput properties exists for the container or @@ -751,7 +759,9 @@ def read_offer(self, **kwargs): def get_throughput(self, **kwargs): # type: (Any) -> ThroughputProperties """Get the ThroughputProperties object for this database. + If no ThroughputProperties already exist for the database, an exception is raised. + :keyword Callable response_hook: A callable invoked with the response metadata. :returns: ThroughputProperties for the database. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: No throughput properties exists for the container or @@ -782,6 +792,7 @@ def replace_throughput(self, throughput, **kwargs): """Replace the database-level throughput. :param throughput: The throughput to be set (an integer). + :type throughput: Union[int, ThroughputProperties] :keyword Callable response_hook: A callable invoked with the response metadata. :returns: ThroughputProperties for the database, updated with new throughput. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/documents.py b/sdk/cosmos/azure-cosmos/azure/cosmos/documents.py index b5058664e015..955a26f9c5ad 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/documents.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/documents.py @@ -71,12 +71,16 @@ def __init__(self): @property def WritableLocations(self): """The list of writable locations for a geo-replicated database account. + :returns: List of writable locations for the database account. + :rtype: List[str] """ return self._WritableLocations @property def ReadableLocations(self): """The list of readable locations for a geo-replicated database account. + :returns: List of readable locations for the database account. + :rtype: List[str] """ return self._ReadableLocations diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/scripts.py b/sdk/cosmos/azure-cosmos/azure/cosmos/scripts.py index 1dae41766a13..3fc399b6659f 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/scripts.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/scripts.py @@ -74,14 +74,15 @@ def list_stored_procedures(self, max_item_count=None, **kwargs): ) def query_stored_procedures(self, query, parameters=None, max_item_count=None, **kwargs): - # type: (str, Optional[List[str]], Optional[int], Any) -> Iterable[Dict[str, Any]] + # type: (str, Optional[List[Dict[str, Any]]], Optional[int], Any) -> Iterable[Dict[str, Any]] """Return all stored procedures matching the given `query`. - :param query: The Azure Cosmos DB SQL query to execute. + :param str query: The Azure Cosmos DB SQL query to execute. :param parameters: Optional array of parameters to the query. Ignored if no query is provided. - :param max_item_count: Max number of items to be returned in the enumeration operation. + :type parameters: List[Dict[str, Any]] + :param int max_item_count: Max number of items to be returned in the enumeration operation. :returns: An Iterable of stored procedures (dicts). - :rtype: Iterable[dict[str, Any]] + :rtype: Iterable[Dict[str, Any]] """ feed_options = build_options(kwargs) if max_item_count is not None: @@ -99,9 +100,10 @@ def get_stored_procedure(self, sproc, **kwargs): """Get the stored procedure identified by `id`. :param sproc: The ID (name) or dict representing stored procedure to retrieve. + :type sproc: Union[str, Dict[str, Any]] :returns: A dict representing the retrieved stored procedure. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the given stored procedure couldn't be retrieved. - :rtype: dict[str, Any] + :rtype: Dict[str, Any] """ request_options = build_options(kwargs) @@ -115,10 +117,10 @@ def create_stored_procedure(self, body, **kwargs): To replace an existing sproc, use the :func:`Container.scripts.replace_stored_procedure` method. - :param body: A dict-like object representing the sproc to create. + :param Dict[str, Any] body: A dict-like object representing the sproc to create. :returns: A dict representing the new stored procedure. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the given stored procedure couldn't be created. - :rtype: dict[str, Any] + :rtype: Dict[str, Any] """ request_options = build_options(kwargs) @@ -133,11 +135,12 @@ def replace_stored_procedure(self, sproc, body, **kwargs): If the stored procedure does not already exist in the container, an exception is raised. :param sproc: The ID (name) or dict representing stored procedure to be replaced. - :param body: A dict-like object representing the sproc to replace. + :type sproc: Union[str, Dict[str, Any]] + :param Dict[str, Any] body: A dict-like object representing the sproc to replace. :returns: A dict representing the stored procedure after replace went through. - :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the replace failed or the stored + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the replace operation failed or the stored procedure with given id does not exist. - :rtype: dict[str, Any] + :rtype: Dict[str, Any] """ request_options = build_options(kwargs) @@ -155,6 +158,7 @@ def delete_stored_procedure(self, sproc, **kwargs): If the stored procedure does not already exist in the container, an exception is raised. :param sproc: The ID (name) or dict representing stored procedure to be deleted. + :type sproc: Union[str, Dict[str, Any]] :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The sproc wasn't deleted successfully. :raises ~azure.cosmos.exceptions.CosmosResourceNotFoundError: The sproc does not exist in the container. :rtype: None @@ -169,7 +173,7 @@ def execute_stored_procedure( self, sproc, # type: Union[str, Dict[str, Any]] partition_key=None, # type: Optional[str] - params=None, # type: Optional[List[Any]] + params=None, # type: Optional[List[Dict[str, Any]]] enable_script_logging=None, # type: Optional[bool] **kwargs # type: Any ): @@ -179,13 +183,16 @@ def execute_stored_procedure( If the stored procedure does not already exist in the container, an exception is raised. :param sproc: The ID (name) or dict representing stored procedure to be executed. + :type sproc: Union[str, Dict[str, Any]] :param partition_key: Specifies the partition key to indicate which partition the sproc should execute on. + :type partition_key: Union[str, int, float, bool] :param params: List of parameters to be passed to the stored procedure to be executed. + :type params: List[Dict[str, Any]] :param bool enable_script_logging: Enables or disables script logging for the current request. :returns: Result of the executed stored procedure for the given parameters. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the stored procedure execution failed - or if the stored procedure with given id does not exists in the container. - :rtype: dict[str, Any] + or if the stored procedure with given id does not exist in the container. + :rtype: Dict[str, Any] """ request_options = build_options(kwargs) @@ -209,9 +216,9 @@ def list_triggers(self, max_item_count=None, **kwargs): # type: (Optional[int], Any) -> Iterable[Dict[str, Any]] """List all triggers in the container. - :param max_item_count: Max number of items to be returned in the enumeration operation. + :param int max_item_count: Max number of items to be returned in the enumeration operation. :returns: An Iterable of triggers (dicts). - :rtype: Iterable[dict[str, Any]] + :rtype: Iterable[Dict[str, Any]] """ feed_options = build_options(kwargs) if max_item_count is not None: @@ -222,12 +229,13 @@ def list_triggers(self, max_item_count=None, **kwargs): ) def query_triggers(self, query, parameters=None, max_item_count=None, **kwargs): - # type: (str, Optional[List[str]], Optional[int], Any) -> Iterable[Dict[str, Any]] + # type: (str, Optional[List[Dict[str, Any]]], Optional[int], Any) -> Iterable[Dict[str, Any]] """Return all triggers matching the given `query`. - :param query: The Azure Cosmos DB SQL query to execute. + :param str query: The Azure Cosmos DB SQL query to execute. :param parameters: Optional array of parameters to the query. Ignored if no query is provided. - :param max_item_count: Max number of items to be returned in the enumeration operation. + :type parameters: List[Dict[str, Any]] + :param int max_item_count: Max number of items to be returned in the enumeration operation. :returns: An Iterable of triggers (dicts). :rtype: Iterable[dict[str, Any]] """ @@ -247,9 +255,10 @@ def get_trigger(self, trigger, **kwargs): """Get a trigger identified by `id`. :param trigger: The ID (name) or dict representing trigger to retrieve. + :type trigger: Union[str, Dict[str, Any]] :returns: A dict representing the retrieved trigger. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the given trigger couldn't be retrieved. - :rtype: dict[str, Any] + :rtype: Dict[str, Any] """ request_options = build_options(kwargs) @@ -263,10 +272,10 @@ def create_trigger(self, body, **kwargs): To replace an existing trigger, use the :func:`ContainerProxy.scripts.replace_trigger` method. - :param body: A dict-like object representing the trigger to create. + :param Dict[str, Any] body: A dict-like object representing the trigger to create. :returns: A dict representing the new trigger. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the given trigger couldn't be created. - :rtype: dict[str, Any] + :rtype: Dict[str, Any] """ request_options = build_options(kwargs) @@ -281,11 +290,12 @@ def replace_trigger(self, trigger, body, **kwargs): If the trigger does not already exist in the container, an exception is raised. :param trigger: The ID (name) or dict representing trigger to be replaced. - :param body: A dict-like object representing the trigger to replace. + :type trigger: Union[str, Dict[str, Any]] + :param Dict[str, Any] body: A dict-like object representing the trigger to replace. :returns: A dict representing the trigger after replace went through. - :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the replace failed or the trigger with given - id does not exist. - :rtype: dict[str, Any] + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the replace operation failed or the trigger + with given id does not exist. + :rtype: Dict[str, Any] """ request_options = build_options(kwargs) @@ -303,6 +313,7 @@ def delete_trigger(self, trigger, **kwargs): If the trigger does not already exist in the container, an exception is raised. :param trigger: The ID (name) or dict representing trigger to be deleted. + :type trigger: Union[str, Dict[str, Any]] :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The trigger wasn't deleted successfully. :raises ~azure.cosmos.exceptions.CosmosResourceNotFoundError: The trigger does not exist in the container. :rtype: None @@ -317,9 +328,9 @@ def list_user_defined_functions(self, max_item_count=None, **kwargs): # type: (Optional[int], Any) -> Iterable[Dict[str, Any]] """List all the user-defined functions in the container. - :param max_item_count: Max number of items to be returned in the enumeration operation. + :param int max_item_count: Max number of items to be returned in the enumeration operation. :returns: An Iterable of user-defined functions (dicts). - :rtype: Iterable[dict[str, Any]] + :rtype: Iterable[Dict[str, Any]] """ feed_options = build_options(kwargs) if max_item_count is not None: @@ -330,14 +341,15 @@ def list_user_defined_functions(self, max_item_count=None, **kwargs): ) def query_user_defined_functions(self, query, parameters=None, max_item_count=None, **kwargs): - # type: (str, Optional[List[str]], Optional[int], Any) -> Iterable[Dict[str, Any]] + # type: (str, Optional[List[Dict[str, Any]]], Optional[int], Any) -> Iterable[Dict[str, Any]] """Return user-defined functions matching a given `query`. - :param query: The Azure Cosmos DB SQL query to execute. + :param str query: The Azure Cosmos DB SQL query to execute. :param parameters: Optional array of parameters to the query. Ignored if no query is provided. - :param max_item_count: Max number of items to be returned in the enumeration operation. + :type parameters: List[Dict[str, Any]] + :param int max_item_count: Max number of items to be returned in the enumeration operation. :returns: An Iterable of user-defined functions (dicts). - :rtype: Iterable[dict[str, Any]] + :rtype: Iterable[Dict[str, Any]] """ feed_options = build_options(kwargs) if max_item_count is not None: @@ -355,9 +367,10 @@ def get_user_defined_function(self, udf, **kwargs): """Get a user-defined functions identified by `id`. :param udf: The ID (name) or dict representing udf to retrieve. + :type udf: Union[str, Dict[str, Any]] :returns: A dict representing the retrieved user-defined function. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the user-defined function couldn't be retrieved. - :rtype: Iterable[dict[str, Any]] + :rtype: Iterable[Dict[str, Any]] """ request_options = build_options(kwargs) @@ -371,10 +384,10 @@ def create_user_defined_function(self, body, **kwargs): To replace an existing UDF, use the :func:`ContainerProxy.scripts.replace_user_defined_function` method. - :param body: A dict-like object representing the udf to create. + :param Dict[str, Any] body: A dict-like object representing the udf to create. :returns: A dict representing the new user-defined function. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the user-defined function couldn't be created. - :rtype: dict[str, Any] + :rtype: Dict[str, Any] """ request_options = build_options(kwargs) @@ -389,11 +402,12 @@ def replace_user_defined_function(self, udf, body, **kwargs): If the UDF does not already exist in the container, an exception is raised. :param udf: The ID (name) or dict representing udf to be replaced. - :param body: A dict-like object representing the udf to replace. + :type udf: Union[str, Dict[str, Any]] + :param Dict[str, Any] body: A dict-like object representing the udf to replace. :returns: A dict representing the user-defined function after replace went through. - :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the replace failed or the user-defined function - with the given id does not exist. - :rtype: dict[str, Any] + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the replace operation failed or the user-defined + function with the given id does not exist. + :rtype: Dict[str, Any] """ request_options = build_options(kwargs) @@ -411,6 +425,7 @@ def delete_user_defined_function(self, udf, **kwargs): If the UDF does not already exist in the container, an exception is raised. :param udf: The ID (name) or dict representing udf to be deleted. + :type udf: Union[str, Dict[str, Any]] :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The udf wasn't deleted successfully. :raises ~azure.cosmos.exceptions.CosmosResourceNotFoundError: The UDF does not exist in the container. :rtype: None diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/user.py b/sdk/cosmos/azure-cosmos/azure/cosmos/user.py index 171bd16665a3..f1e9aa2048f6 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/user.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/user.py @@ -92,10 +92,10 @@ def list_permissions(self, max_item_count=None, **kwargs): # type: (Optional[int], Any) -> Iterable[Dict[str, Any]] """List all permission for the user. - :param max_item_count: Max number of permissions to be returned in the enumeration operation. + :param int max_item_count: Max number of permissions to be returned in the enumeration operation. :keyword Callable response_hook: A callable invoked with the response metadata. :returns: An Iterable of permissions (dicts). - :rtype: Iterable[dict[str, Any]] + :rtype: Iterable[Dict[str, Any]] """ feed_options = build_options(kwargs) response_hook = kwargs.pop('response_hook', None) @@ -117,15 +117,16 @@ def query_permissions( max_item_count=None, **kwargs ): - # type: (str, Optional[List[str]], Optional[int], Any) -> Iterable[Dict[str, Any]] + # type: (str, Optional[List[Dict[str, Any]]], Optional[int], Any) -> Iterable[Dict[str, Any]] """Return all permissions matching the given `query`. - :param query: The Azure Cosmos DB SQL query to execute. + :param str query: The Azure Cosmos DB SQL query to execute. :param parameters: Optional array of parameters to the query. Ignored if no query is provided. - :param max_item_count: Max number of permissions to be returned in the enumeration operation. + :type parameters: List[Dict[str, Any]] + :param int max_item_count: Max number of permissions to be returned in the enumeration operation. :keyword Callable response_hook: A callable invoked with the response metadata. :returns: An Iterable of permissions (dicts). - :rtype: Iterable[dict[str, Any]] + :rtype: Iterable[Dict[str, Any]] """ feed_options = build_options(kwargs) response_hook = kwargs.pop('response_hook', None) @@ -146,15 +147,16 @@ def query_permissions( @distributed_trace def get_permission(self, permission, **kwargs): - # type: (str, Any) -> Permission + # type: (Union[str, Permission, Dict[str, Any]], Any) -> Permission """Get the permission identified by `id`. :param permission: The ID (name), dict representing the properties or :class:`Permission` instance of the permission to be retrieved. + :type permission: Union[str, Permission, Dict[str, Any]] :keyword Callable response_hook: A callable invoked with the response metadata. :returns: A dict representing the retrieved permission. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the given permission couldn't be retrieved. - :rtype: dict[str, Any] + :rtype: Dict[str, Any] """ request_options = build_options(kwargs) response_hook = kwargs.pop('response_hook', None) @@ -181,11 +183,11 @@ def create_permission(self, body, **kwargs): To update or replace an existing permision, use the :func:`UserProxy.upsert_permission` method. - :param body: A dict-like object representing the permission to create. + :param Dict[str, Any] body: A dict-like object representing the permission to create. :keyword Callable response_hook: A callable invoked with the response metadata. :returns: A dict representing the new permission. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the given permission couldn't be created. - :rtype: dict[str, Any] + :rtype: Dict[str, Any] """ request_options = build_options(kwargs) response_hook = kwargs.pop('response_hook', None) @@ -213,11 +215,11 @@ def upsert_permission(self, body, **kwargs): If the permission already exists in the container, it is replaced. If the permission does not exist, it is inserted. - :param body: A dict-like object representing the permission to update or insert. - :param Callable response_hook: A callable invoked with the response metadata. + :param Dict[str, Any] body: A dict-like object representing the permission to update or insert. + :keyword Callable response_hook: A callable invoked with the response metadata. :returns: A dict representing the upserted permission. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the given permission could not be upserted. - :rtype: dict[str, Any] + :rtype: Dict[str, Any] """ request_options = build_options(kwargs) response_hook = kwargs.pop('response_hook', None) @@ -239,19 +241,20 @@ def upsert_permission(self, body, **kwargs): @distributed_trace def replace_permission(self, permission, body, **kwargs): - # type: (str, Dict[str, Any], Any) -> Permission + # type: (Union[str, Permission, Dict[str, Any]], Dict[str, Any], Any) -> Permission """Replaces the specified permission if it exists for the user. If the permission does not already exist, an exception is raised. :param permission: The ID (name), dict representing the properties or :class:`Permission` instance of the permission to be replaced. - :param body: A dict-like object representing the permission to replace. + :type permission: Union[str, Permission, Dict[str, Any]] + :param Dict[str, Any] body: A dict-like object representing the permission to replace. :keyword Callable response_hook: A callable invoked with the response metadata. :returns: A dict representing the permission after replace went through. - :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the replace failed or the permission + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the replace operation failed or the permission with given id does not exist. - :rtype: dict[str, Any] + :rtype: Dict[str, Any] """ request_options = build_options(kwargs) response_hook = kwargs.pop('response_hook', None) @@ -273,13 +276,14 @@ def replace_permission(self, permission, body, **kwargs): @distributed_trace def delete_permission(self, permission, **kwargs): - # type: (str, Any) -> None + # type: (Union[str, Permission, Dict[str, Any]], Any) -> None """Delete the specified permission from the user. If the permission does not already exist, an exception is raised. :param permission: The ID (name), dict representing the properties or :class:`Permission` instance of the permission to be replaced. + :type permission: Union[str, Permission, Dict[str, Any]] :keyword Callable response_hook: A callable invoked with the response metadata. :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The permission wasn't deleted successfully. :raises ~azure.cosmos.exceptions.CosmosResourceNotFoundError: The permission does not exist for the user.