Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Cosmos] Updates to kwargs and docstrings #8277

Merged
merged 14 commits into from
Oct 30, 2019
2 changes: 1 addition & 1 deletion sdk/cosmos/azure-cosmos/azure/cosmos/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from ._version import VERSION
from ._retry_utility import ConnectionRetryPolicy
from .container import ContainerProxy
from .cosmos_client import CosmosClient
Expand All @@ -40,7 +41,6 @@
)
from .partition_key import PartitionKey
from .permission import Permission
from .version import VERSION

__all__ = (
"CosmosClient",
Expand Down
42 changes: 37 additions & 5 deletions sdk/cosmos/azure-cosmos/azure/cosmos/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@
import six
from six.moves.urllib.parse import quote as urllib_quote

from azure.core import MatchConditions

from . import auth
from . import documents
from . import partition_key
Expand Down Expand Up @@ -63,20 +65,50 @@
'continuation': 'continuation',
'is_start_from_beginning': 'isStartFromBeginning',
'populate_partition_key_range_statistics': 'populatePartitionKeyRangeStatistics',
'populate_quota_info': 'populateQuotaInfo'
'populate_quota_info': 'populateQuotaInfo',
'content_type': 'contentType',
'is_query_plan_request': 'isQueryPlanRequest',
'supported_query_features': 'supportedQueryFeatures',
'query_version': 'queryVersion'
}

def _get_match_headers(kwargs):
# type: (Dict[str, Any]) -> Tuple(Optional[str], Optional[str])
if_match = kwargs.pop('if_match', None)
if_none_match = kwargs.pop('if_none_match', None)
match_condition = kwargs.pop('match_condition', None)
if match_condition == MatchConditions.IfNotModified:
if_match = kwargs.pop('etag', None)
if not if_match:
raise ValueError("'match_condition' specified without 'etag'.")
elif match_condition == MatchConditions.IfPresent:
if_match = '*'
elif match_condition == MatchConditions.IfModified:
if_none_match = kwargs.pop('etag', None)
if not if_none_match:
raise ValueError("'match_condition' specified without 'etag'.")
elif match_condition == MatchConditions.IfMissing:
if_none_match = '*'
elif match_condition is None:
if 'etag' in kwargs:
raise ValueError("'etag' specified without 'match_condition'.")
else:
raise TypeError("Invalid match condition: {}".format(match_condition))
return if_match, if_none_match


def build_options(kwargs):
# type: (Dict[str, Any]) -> Dict[str, Any]
options = kwargs.pop('request_options', kwargs.pop('feed_options', {}))
for key, value in _COMMON_OPTIONS.items():
if key in kwargs:
options[value] = kwargs.pop(key)

if 'if_match' in kwargs:
options['accessCondition'] = {'type': 'IfMatch', 'condition': kwargs.pop('if_match')}
if 'if_none_match' in kwargs:
options['accessCondition'] = {'type': 'IfNoneMatch', 'condition': kwargs.pop('if_none_match')}
if_match, if_none_match = _get_match_headers(kwargs)
if if_match:
options['accessCondition'] = {'type': 'IfMatch', 'condition': if_match}
if if_none_match:
options['accessCondition'] = {'type': 'IfNoneMatch', 'condition': if_none_match}
return options


Expand Down
2 changes: 1 addition & 1 deletion sdk/cosmos/azure-cosmos/azure/cosmos/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

import platform
import re
from .version import VERSION
from ._version import VERSION


def get_user_agent():
Expand Down
140 changes: 61 additions & 79 deletions sdk/cosmos/azure-cosmos/azure/cosmos/container.py

Large diffs are not rendered by default.

144 changes: 53 additions & 91 deletions sdk/cosmos/azure-cosmos/azure/cosmos/cosmos_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,53 +126,31 @@ class CosmosClient(object):
Use this client to configure and execute requests to the Azure Cosmos DB service.

:param str url: The URL of the Cosmos DB account.
:param credential:
Can be the account key, or a dictionary of resource tokens.
:param credential: Can be the account key, or a dictionary of resource tokens.
:type credential: str or dict[str, str]
:param str consistency_level:
Consistency level to use for the session. The default value is "Session".

**Keyword arguments:**

*timeout* - An absolute timeout in seconds, for the combined HTTP request and response processing.

*request_timeout* - The HTTP request timeout in seconds.

*media_request_timeout* - The media request timeout in seconds.

*connection_mode* - The connection mode for the client - currently only supports 'Gateway'.

*media_read_mode* - The mode for use with downloading attachment content - default value is `Buffered`.

*proxy_config* - Instance of `azure.cosmos.ProxyConfiguration`.

*ssl_config* - Instance of `azure.cosmos.SSLConfiguration`.

*connection_verify* - Whether to verify the connection, default value is True.

*connection_cert* - An alternative certificate to verify the connection.

*retry_total* - Maximum retry attempts.

*retry_backoff_max* - Maximum retry wait time in seconds.

*retry_fixed_interval* - Fixed retry interval in milliseconds.

*retry_read* - Maximum number of socket read retry attempts.

*retry_connect* - Maximum number of connection error retry attempts.

*retry_status* - Maximum number of retry attempts on error status codes.

*retry_on_status_codes* - A list of specific status codes to retry on.

*retry_backoff_factor* - Factor to calculate wait time between retry attempts.

*enable_endpoint_discovery* - Enable endpoint discovery for geo-replicated database accounts. Default is True.

*preferred_locations* - The preferred locations for geo-replicated database accounts.

*connection_policy* - An instance of `azure.cosmos.documents.ConnectionPolicy`
:param str consistency_level: Consistency level to use for the session. The default value is "Session".
:keyword int timeout: An absolute timeout in seconds, for the combined HTTP request and response processing.
:keyword int request_timeout: The HTTP request timeout in seconds.
:keyword int media_request_timeout: The media request timeout in seconds.
:keyword str connection_mode: The connection mode for the client - currently only supports 'Gateway'.
:keyword str media_read_mode: The mode for use with downloading attachment content - default value is `Buffered`.
:keyword proxy_config: Connection proxy configuration.
:paramtype proxy_config: ~azure.cosmos.ProxyConfiguration
:keyword ssl_config: Connection SSL configuration.
:paramtype ssl_config: ~azure.cosmos.SSLConfiguration
:keyword bool connection_verify: Whether to verify the connection, default value is True.
:keyword str connection_cert: An alternative certificate to verify the connection.
:keyword int retry_total: Maximum retry attempts.
:keyword int retry_backoff_max: Maximum retry wait time in seconds.
:keyword int retry_fixed_interval: Fixed retry interval in milliseconds.
:keyword int retry_read: Maximum number of socket read retry attempts.
:keyword int retry_connect: Maximum number of connection error retry attempts.
:keyword int retry_status: Maximum number of retry attempts on error status codes.
:keyword list[int] retry_on_status_codes: A list of specific status codes to retry on.
:keyword float retry_backoff_factor: Factor to calculate wait time between retry attempts.
:keyword bool enable_endpoint_discovery: Enable endpoint discovery for geo-replicated database accounts.
Default is True.
:keyword list[str] preferred_locations: The preferred locations for geo-replicated database accounts.

.. admonition:: Example:

Expand Down Expand Up @@ -253,16 +231,14 @@ 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 session_token: Token for use with Session consistency.
:param initial_headers: Initial headers to be sent as part of the request.
:type initial_headers: dict[str, str]
:param access_condition: Conditions Associated with the request.
:type access_condition: dict[str, str]
:param bool populate_query_metrics: Enable returning query metrics in response headers.
:param int offer_throughput: The provisioned throughput for this offer.
:param request_options: Dictionary of additional properties to be used for the request.
:type request_options: dict[str, Any]
:param Callable response_hook: a callable invoked with the response metadata
: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 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 DatabaseProxy instance representing the new database.
:rtype: ~azure.cosmos.DatabaseProxy
:raises ~azure.cosmos.exceptions.CosmosResourceExistsError: Database with the given ID already exists.
Expand Down Expand Up @@ -307,16 +283,14 @@ def create_database_if_not_exists( # pylint: disable=redefined-builtin
if they differ from what was passed into the method.

:param id: ID (name) of the database to read or create.
:param str session_token: Token for use with Session consistency.
:param initial_headers: Initial headers to be sent as part of the request.
:type initial_headers: dict[str, str]
:param access_condition: Conditions Associated with the request.
:type access_condition: dict[str, str]
:param bool populate_query_metrics: Enable returning query metrics in response headers.
:param int offer_throughput: The provisioned throughput for this offer.
:param request_options: Dictionary of additional properties to be used for the request.
:type request_options: dict[str, Any]
:param Callable response_hook: a callable invoked with the response metadata
: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 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 DatabaseProxy instance representing the database.
:rtype: ~azure.cosmos.DatabaseProxy
:raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The database read or creation failed.
Expand All @@ -338,8 +312,7 @@ def create_database_if_not_exists( # pylint: disable=redefined-builtin

def get_database_client(self, database):
# type: (Union[str, DatabaseProxy, Dict[str, Any]]) -> DatabaseProxy
"""
Retrieve an existing database with the ID (name) `id`.
"""Retrieve an existing database with the ID (name) `id`.

:param database: The ID (name), dict representing the properties or `DatabaseProxy`
instance of the database to read.
Expand All @@ -364,17 +337,13 @@ def list_databases(
**kwargs # type: Any
):
# type: (...) -> Iterable[Dict[str, Any]]
"""
List the databases in a Cosmos DB SQL database account.
"""List the databases in a Cosmos DB SQL database account.

:param int max_item_count: Max number of items to be returned in the enumeration operation.
:param str session_token: Token for use with Session consistency.
:param initial_headers: Initial headers to be sent as part of the request.
:type initial_headers: dict[str, str]
:param bool populate_query_metrics: Enable returning query metrics in response headers.
:param feed_options: Dictionary of additional properties to be used for the request.
:type feed_options: dict[str, str]
:param Callable response_hook: a callable invoked with the response metadata
: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 Callable response_hook: A callable invoked with the response metadata.
:returns: An Iterable of database properties (dicts).
:rtype: Iterable[dict[str, str]]
"""
Expand All @@ -401,21 +370,17 @@ def query_databases(
**kwargs # type: Any
):
# type: (...) -> Iterable[Dict[str, Any]]
"""
Query the databases in a Cosmos DB SQL database account.
"""Query the databases in a Cosmos DB SQL database account.

:param str query: The Azure Cosmos DB SQL query to execute.
:param list[str] parameters: Optional array of parameters to the query. Ignored if no query is provided.
:param bool enable_cross_partition_query: Allow scan on the queries which couldn't be
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.
:param str session_token: Token for use with Session consistency.
:param initial_headers: Initial headers to be sent as part of the request.
:type initial_headers: dict[str, str]
:param bool populate_query_metrics: Enable returning query metrics in response headers.
:param feed_options: Dictionary of additional properties to be used for the request.
:type feed_options: dict[str, Any]
:param Callable response_hook: a callable invoked with the response metadata
: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 Callable response_hook: A callable invoked with the response metadata.
:returns: An Iterable of database properties (dicts).
:rtype: Iterable[dict[str, str]]
"""
Expand Down Expand Up @@ -450,21 +415,18 @@ def delete_database(
**kwargs # type: Any
):
# type: (...) -> None
"""
Delete the database with the given ID (name).
"""Delete the database with the given ID (name).

: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
:param str session_token: Token for use with Session consistency.
:param initial_headers: Initial headers to be sent as part of the request.
:type initial_headers: dict[str, str]
:param access_condition: Conditions Associated with the request.
:type access_condition: dict[str, str]
:param bool populate_query_metrics: Enable returning query metrics in response headers.
:param request_options: Dictionary of additional properties to be used for the request.
:type request_options: dict[str, Any]
:param Callable response_hook: a callable invoked with the response metadata
: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 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.
:raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the database couldn't be deleted.
:rtype: None
"""
Expand All @@ -484,7 +446,7 @@ def get_database_account(self, **kwargs):
"""
Retrieve the database account information.

:param Callable response_hook: a callable invoked with the response metadata
:keyword Callable response_hook: A callable invoked with the response metadata.
:returns: A `DatabaseAccount` instance representing the Cosmos DB Database Account.
:rtype: ~azure.cosmos.DatabaseAccount
"""
Expand Down
Loading