Skip to content

Commit 6e5bd48

Browse files
FabianMeiswinkelannatisch
authored andcommitted
Enabling option to disable response payload on writes (Azure#37365)
* Initial draft * Adding tests * Renaming parameter * Update container.py * Renaming test file * Fixing LINT issues * Update container.py * Update _base.py * Update _base.py * Fixing tests * Fixing tests * Adding support to disable response payload on write for AIO * Update CHANGELOG.md * Update _cosmos_client.py * Reacting to code review comments * Addressing code review feedback * Addressed CR feedback * Fixing pyLint errors * Fixing pylint errors * Update test_crud.py * Fixing svc regression * Update sdk/cosmos/azure-cosmos/azure/cosmos/aio/_container.py Co-authored-by: Anna Tisch <[email protected]> * Reacting to code review feedback. * Update container.py * Update test_query_vector_similarity.py --------- Co-authored-by: Anna Tisch <[email protected]>
1 parent 5d8ca40 commit 6e5bd48

11 files changed

+5483
-38
lines changed

sdk/cosmos/azure-cosmos/CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
#### Features Added
66
* Added Retry Policy for Container Recreate in the Python SDK. See [PR 36043](https://github.com/Azure/azure-sdk-for-python/pull/36043)
7+
* Added option to disable write payload on writes. See [PR 37365](https://github.com/Azure/azure-sdk-for-python/pull/37365)
78

89
#### Breaking Changes
910

sdk/cosmos/azure-cosmos/azure/cosmos/_base.py

+11-1
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,8 @@
6060
'is_query_plan_request': 'isQueryPlanRequest',
6161
'supported_query_features': 'supportedQueryFeatures',
6262
'query_version': 'queryVersion',
63-
'priority': 'priorityLevel'
63+
'priority': 'priorityLevel',
64+
'no_response': 'responsePayloadOnWriteDisabled'
6465
}
6566

6667
# Cosmos resource ID validation regex breakdown:
@@ -318,6 +319,15 @@ def GetHeaders( # pylint: disable=too-many-statements,too-many-branches
318319
if options.get("correlatedActivityId"):
319320
headers[http_constants.HttpHeaders.CorrelatedActivityId] = options["correlatedActivityId"]
320321

322+
if resource_type == "docs" and verb != "get":
323+
if "responsePayloadOnWriteDisabled" in options:
324+
responsePayloadOnWriteDisabled = options["responsePayloadOnWriteDisabled"]
325+
else:
326+
responsePayloadOnWriteDisabled = cosmos_client_connection.connection_policy.ResponsePayloadOnWriteDisabled
327+
328+
if responsePayloadOnWriteDisabled:
329+
headers[http_constants.HttpHeaders.Prefer] = "return=minimal"
330+
321331
# If it is an operation at the container level, verify the rid of the container to see if the cache needs to be
322332
# refreshed.
323333
if resource_type != 'dbs' and options.get("containerRID"):

sdk/cosmos/azure-cosmos/azure/cosmos/aio/_container.py

+36-8
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,7 @@ async def create_item(
190190
etag: Optional[str] = None,
191191
match_condition: Optional[MatchConditions] = None,
192192
priority: Optional[Literal["High", "Low"]] = None,
193+
no_response: Optional[bool] = None,
193194
**kwargs: Any
194195
) -> Dict[str, Any]:
195196
"""Create an item in the container.
@@ -216,7 +217,10 @@ async def create_item(
216217
request. Once the user has reached their provisioned throughput, low priority requests are throttled
217218
before high priority requests start getting throttled. Feature must first be enabled at the account level.
218219
:raises ~azure.cosmos.exceptions.CosmosHttpResponseError: Item with the given ID already exists.
219-
:returns: A dict representing the new item.
220+
:keyword bool no_response: Indicates whether service should be instructed to skip
221+
sending response payloads. When not specified explicitly here, the default value will be determined from
222+
client-level options.
223+
:returns: A dict representing the new item. The dict will be empty if `no_response` is specified.
220224
:rtype: Dict[str, Any]
221225
"""
222226
if pre_trigger_include is not None:
@@ -233,6 +237,8 @@ async def create_item(
233237
kwargs['etag'] = etag
234238
if match_condition is not None:
235239
kwargs['match_condition'] = match_condition
240+
if no_response is not None:
241+
kwargs['no_response'] = no_response
236242
request_options = _build_options(kwargs)
237243
request_options["disableAutomaticIdGeneration"] = not enable_automatic_id_generation
238244
if indexing_directive is not None:
@@ -243,7 +249,7 @@ async def create_item(
243249
result = await self.client_connection.CreateItem(
244250
database_or_container_link=self.container_link, document=body, options=request_options, **kwargs
245251
)
246-
return result
252+
return result or {}
247253

248254
@distributed_trace_async
249255
async def read_item(
@@ -552,6 +558,7 @@ async def upsert_item(
552558
etag: Optional[str] = None,
553559
match_condition: Optional[MatchConditions] = None,
554560
priority: Optional[Literal["High", "Low"]] = None,
561+
no_response: Optional[bool] = None,
555562
**kwargs: Any
556563
) -> Dict[str, Any]:
557564
"""Insert or update the specified item.
@@ -574,7 +581,11 @@ async def upsert_item(
574581
request. Once the user has reached their provisioned throughput, low priority requests are throttled
575582
before high priority requests start getting throttled. Feature must first be enabled at the account level.
576583
:raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The given item could not be upserted.
577-
:returns: A dict representing the upserted item.
584+
:keyword bool no_response: Indicates whether service should be instructed to skip
585+
sending response payloads. When not specified explicitly here, the default value will be determined from
586+
client-level options.
587+
:returns: A dict representing the item after the upsert operation went through. The dict will be empty if
588+
`no_response` is specified.
578589
:rtype: Dict[str, Any]
579590
"""
580591
if pre_trigger_include is not None:
@@ -591,6 +602,8 @@ async def upsert_item(
591602
kwargs['etag'] = etag
592603
if match_condition is not None:
593604
kwargs['match_condition'] = match_condition
605+
if no_response is not None:
606+
kwargs['no_response'] = no_response
594607
request_options = _build_options(kwargs)
595608
request_options["disableAutomaticIdGeneration"] = True
596609
if self.container_link in self.__get_client_container_caches():
@@ -602,7 +615,7 @@ async def upsert_item(
602615
options=request_options,
603616
**kwargs
604617
)
605-
return result
618+
return result or {}
606619

607620
@distributed_trace_async
608621
async def replace_item(
@@ -617,6 +630,7 @@ async def replace_item(
617630
etag: Optional[str] = None,
618631
match_condition: Optional[MatchConditions] = None,
619632
priority: Optional[Literal["High", "Low"]] = None,
633+
no_response: Optional[bool] = None,
620634
**kwargs: Any
621635
) -> Dict[str, Any]:
622636
"""Replaces the specified item if it exists in the container.
@@ -641,7 +655,11 @@ async def replace_item(
641655
before high priority requests start getting throttled. Feature must first be enabled at the account level.
642656
:raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The replace failed or the item with
643657
given id does not exist.
644-
:returns: A dict representing the item after replace went through.
658+
:keyword bool no_response: Indicates whether service should be instructed to skip
659+
sending response payloads. When not specified explicitly here, the default value will be determined from
660+
client-level options.
661+
:returns: A dict representing the item after replace went through. The dict will be empty if `no_response`
662+
is specified.
645663
:rtype: Dict[str, Any]
646664
"""
647665
item_link = self._get_document_link(item)
@@ -659,6 +677,8 @@ async def replace_item(
659677
kwargs['etag'] = etag
660678
if match_condition is not None:
661679
kwargs['match_condition'] = match_condition
680+
if no_response is not None:
681+
kwargs['no_response'] = no_response
662682
request_options = _build_options(kwargs)
663683
request_options["disableAutomaticIdGeneration"] = True
664684
if self.container_link in self.__get_client_container_caches():
@@ -667,7 +687,7 @@ async def replace_item(
667687
result = await self.client_connection.ReplaceItem(
668688
document_link=item_link, new_document=body, options=request_options, **kwargs
669689
)
670-
return result
690+
return result or {}
671691

672692
@distributed_trace_async
673693
async def patch_item(
@@ -683,6 +703,7 @@ async def patch_item(
683703
etag: Optional[str] = None,
684704
match_condition: Optional[MatchConditions] = None,
685705
priority: Optional[Literal["High", "Low"]] = None,
706+
no_response: Optional[bool] = None,
686707
**kwargs: Any
687708
) -> Dict[str, Any]:
688709
""" Patches the specified item with the provided operations if it
@@ -707,7 +728,11 @@ async def patch_item(
707728
:keyword Literal["High", "Low"] priority: Priority based execution allows users to set a priority for each
708729
request. Once the user has reached their provisioned throughput, low priority requests are throttled
709730
before high priority requests start getting throttled. Feature must first be enabled at the account level.
710-
:returns: A dict representing the item after the patch operations went through.
731+
:keyword bool no_response: Indicates whether service should be instructed to skip
732+
sending response payloads. When not specified explicitly here, the default value will be determined from
733+
client-level options.
734+
:returns: A dict representing the item after the patch operation went through. The dict will be empty if
735+
`no_response` is specified.
711736
:raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The patch operations failed or the item with
712737
given id does not exist.
713738
:rtype: dict[str, Any]
@@ -724,6 +749,8 @@ async def patch_item(
724749
kwargs['etag'] = etag
725750
if match_condition is not None:
726751
kwargs['match_condition'] = match_condition
752+
if no_response is not None:
753+
kwargs['no_response'] = no_response
727754
request_options = _build_options(kwargs)
728755
request_options["disableAutomaticIdGeneration"] = True
729756
request_options["partitionKey"] = await self._set_partition_key(partition_key)
@@ -733,8 +760,9 @@ async def patch_item(
733760
request_options["containerRID"] = self.__get_client_container_caches()[self.container_link]["_rid"]
734761

735762
item_link = self._get_document_link(item)
736-
return await self.client_connection.PatchItem(
763+
result = await self.client_connection.PatchItem(
737764
document_link=item_link, operations=patch_operations, options=request_options, **kwargs)
765+
return result or {}
738766

739767
@distributed_trace_async
740768
async def delete_item(

sdk/cosmos/azure-cosmos/azure/cosmos/aio/_cosmos_client.py

+3
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ def _build_connection_policy(kwargs: Dict[str, Any]) -> ConnectionPolicy:
113113
retry_backoff_factor=kwargs.pop('retry_backoff_factor', 0.8),
114114
)
115115
policy.ConnectionRetryConfiguration = connection_retry
116+
policy.ResponsePayloadOnWriteDisabled = kwargs.pop('no_response_on_write', False)
116117
return policy
117118

118119

@@ -156,6 +157,8 @@ class CosmosClient: # pylint: disable=client-accepts-api-version-keyword
156157
Must be used along with a logger to work.
157158
:keyword ~logging.Logger logger: Logger to be used for collecting request diagnostics. Can be passed in at client
158159
level (to log all requests) or at a single request level. Requests will be logged at INFO level.
160+
:keyword bool no_response_on_write: Indicates whether service should be instructed to skip sending
161+
response payloads for write operations on items by default unless specified differently per operation.
159162
160163
.. admonition:: Example:
161164

0 commit comments

Comments
 (0)