-
Notifications
You must be signed in to change notification settings - Fork 5.8k
Python: S3 Conditional Requests scenario #7018
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
Merged
cpyle0819
merged 11 commits into
awsdocs:main
from
rlhagerm:python-conditional-requests
Oct 29, 2024
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
43455a2
Adding files.
rlhagerm 7ff766e
Adding scenario files.
rlhagerm ab85ac6
Updates to scenario.
rlhagerm f5be0c2
Cleanup and adding test file.
rlhagerm a79f6be
Metadata updates.
rlhagerm 3469ed2
Updates to specification.
rlhagerm 5eecd51
Removing unused files.
rlhagerm 05745b2
Update to README.
rlhagerm 3762430
Remove unused file, update README in scenario folder.
rlhagerm c0b2cf8
Fix output statement.
rlhagerm 5814230
Updates to requirements.txt
rlhagerm File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,3 @@ | ||
| boto3>=1.34.4 | ||
| boto3>=1.35.49 | ||
| pytest>=7.2.1 | ||
| requests>=2.28.2 |
53 changes: 53 additions & 0 deletions
53
python/example_code/s3/scenarios/conditional_requests/README.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
|
|
||
| # Amazon S3 Conditional Requests Feature Scenario for the SDK for Python (boto3) | ||
|
|
||
| ## Overview | ||
|
|
||
| This example demonstrates how to use the AWS SDK for Python (boto3) to work with Amazon Simple Storage Service (Amazon S3) conditional request features. The scenario demonstrates how to add preconditions to S3 operations, and how those operations will succeed or fail based on the conditional requests. | ||
|
|
||
| [Amazon S3 Conditional Requests](https://docs.aws.amazon.com/AmazonS3/latest/userguide/conditional-requests.html) are used to add preconditions to S3 read, copy, or write requests. | ||
|
|
||
| ## ⚠ Important | ||
|
|
||
| - Running this code might result in charges to your AWS account. For more details, see [AWS Pricing](https://aws.amazon.com/pricing/) and [Free Tier](https://aws.amazon.com/free/). | ||
| - Running the tests might result in charges to your AWS account. | ||
| - We recommend that you grant your code least privilege. At most, grant only the minimum permissions required to perform the task. For more information, see [Grant least privilege](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege). | ||
| - This code is not tested in every AWS Region. For more information, see [AWS Regional Services](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services). | ||
|
|
||
| ## Code examples | ||
|
|
||
| ### Prerequisites | ||
|
|
||
| To run these examples, you need: | ||
|
|
||
| - Python 3.x installed. | ||
| - Run `python pip install -r requirements.txt` | ||
| - AWS credentials configured. For more information, see [Configuring the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html). | ||
|
|
||
| ### Scenario | ||
|
|
||
| This example uses a feature scenario to demonstrate various aspects of S3 conditional requests. The scenario is divided into three stages: | ||
|
|
||
| 1. **Setup**: Create test buckets and objects. | ||
| 2. **Conditional Reads and Writes**: Explore S3 conditional requests by listing objects, attempting to read or write with conditional requests, and viewing request results. | ||
| 3. **Clean**: Delete all objects and buckets. | ||
|
|
||
| #### Running the scenario | ||
| To run this feature scenario, run the command below from this directory: | ||
|
|
||
| ``` | ||
| python scenario.py | ||
| ``` | ||
|
|
||
|
|
||
| ## Additional resources | ||
|
|
||
| - [Amazon S3 Developer Guide](https://docs.aws.amazon.com/AmazonS3/latest/userguide/conditional-requests.html) | ||
| - [Amazon S3 API Reference](https://docs.aws.amazon.com/AmazonS3/latest/API/Welcome.html) | ||
| - [boto3 Amazon S3 reference](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html) | ||
|
|
||
| --- | ||
|
|
||
| © Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
|
|
||
| SPDX-License-Identifier: Apache-2.0 |
142 changes: 142 additions & 0 deletions
142
python/example_code/s3/scenarios/conditional_requests/s3_conditional_requests.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,142 @@ | ||
| # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| # snippet-start:[python.example_code.s3.S3ConditionalRequests.wrapper] | ||
|
|
||
| import boto3 | ||
| import logging | ||
|
|
||
| from botocore.exceptions import ClientError | ||
|
|
||
| # Configure logging | ||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| # snippet-start:[python.example_code.s3.helper.S3ConditionalRequests] | ||
| class S3ConditionalRequests: | ||
| """Encapsulates S3 conditional request operations.""" | ||
|
|
||
| def __init__(self, s3_client): | ||
| self.s3 = s3_client | ||
|
|
||
| @classmethod | ||
| def from_client(cls): | ||
| """ | ||
| Instantiates this class from a Boto3 client. | ||
| """ | ||
| s3_client = boto3.client("s3") | ||
| return cls(s3_client) | ||
|
|
||
| # snippet-end:[python.example_code.s3.helper.S3ConditionalRequests] | ||
|
|
||
| # snippet-start:[python.example_code.s3.GetObjectConditional] | ||
|
|
||
| def get_object_conditional( | ||
| self, | ||
| object_key: str, | ||
| source_bucket: str, | ||
| condition_type: str, | ||
| condition_value: str, | ||
| ): | ||
| """ | ||
| Retrieves an object from Amazon S3 with a conditional request. | ||
|
|
||
| :param object_key: The key of the object to retrieve. | ||
| :param source_bucket: The source bucket of the object. | ||
| :param condition_type: The type of condition: 'IfMatch', 'IfNoneMatch', 'IfModifiedSince', 'IfUnmodifiedSince'. | ||
| :param condition_value: The value to use for the condition. | ||
| """ | ||
| try: | ||
| response = self.s3.get_object( | ||
| Bucket=source_bucket, | ||
| Key=object_key, | ||
| **{condition_type: condition_value}, | ||
| ) | ||
| sample_bytes = response["Body"].read(20) | ||
| print( | ||
| f"\tConditional read successful. Here are the first 20 bytes of the object:\n" | ||
| ) | ||
| print(f"\t{sample_bytes}") | ||
| except ClientError as e: | ||
| error_code = e.response["Error"]["Code"] | ||
| if error_code == "PreconditionFailed": | ||
| print("\tConditional read failed: Precondition failed") | ||
| elif error_code == "304": # Not modified error code. | ||
| print("\tConditional read failed: Object not modified") | ||
| else: | ||
| logger.error(f"Unexpected error: {error_code}") | ||
| raise | ||
|
|
||
| # snippet-end:[python.example_code.s3.GetObjectConditional] | ||
|
|
||
| # snippet-start:[python.example_code.s3.PutObjectConditional] | ||
|
|
||
| def put_object_conditional(self, object_key: str, source_bucket: str, data: bytes): | ||
| """ | ||
| Uploads an object to Amazon S3 with a conditional request. Prevents overwrite | ||
| using an IfNoneMatch condition for the object key. | ||
|
|
||
| :param object_key: The key of the object to upload. | ||
| :param source_bucket: The source bucket of the object. | ||
| :param data: The data to upload. | ||
| """ | ||
| try: | ||
| self.s3.put_object( | ||
| Bucket=source_bucket, Key=object_key, Body=data, IfNoneMatch="*" | ||
| ) | ||
| print( | ||
| f"\tConditional write successful for key {object_key} in bucket {source_bucket}." | ||
| ) | ||
| except ClientError as e: | ||
| error_code = e.response["Error"]["Code"] | ||
| if error_code == "PreconditionFailed": | ||
| print("\tConditional write failed: Precondition failed") | ||
| else: | ||
| logger.error(f"Unexpected error: {error_code}") | ||
| raise | ||
|
|
||
| # snippet-end:[python.example_code.s3.PutObjectConditional] | ||
|
|
||
| # snippet-start:[python.example_code.s3.CopyObjectConditional] | ||
| def copy_object_conditional( | ||
| self, | ||
| source_key: str, | ||
| dest_key: str, | ||
| source_bucket: str, | ||
| dest_bucket: str, | ||
| condition_type: str, | ||
| condition_value: str, | ||
| ): | ||
| """ | ||
| Copies an object from one Amazon S3 bucket to another with a conditional request. | ||
|
|
||
| :param source_key: The key of the source object to copy. | ||
| :param dest_key: The key of the destination object. | ||
| :param source_bucket: The source bucket of the object. | ||
| :param dest_bucket: The destination bucket of the object. | ||
| :param condition_type: The type of condition to apply, e.g. | ||
| 'CopySourceIfMatch', 'CopySourceIfNoneMatch', 'CopySourceIfModifiedSince', 'CopySourceIfUnmodifiedSince'. | ||
| :param condition_value: The value to use for the condition. | ||
| """ | ||
| try: | ||
| self.s3.copy_object( | ||
| Bucket=dest_bucket, | ||
| Key=dest_key, | ||
| CopySource={"Bucket": source_bucket, "Key": source_key}, | ||
| **{condition_type: condition_value}, | ||
| ) | ||
| print( | ||
| f"\tConditional copy successful for key {dest_key} in bucket {dest_bucket}." | ||
| ) | ||
| except ClientError as e: | ||
| error_code = e.response["Error"]["Code"] | ||
| if error_code == "PreconditionFailed": | ||
| print("\tConditional copy failed: Precondition failed") | ||
| elif error_code == "304": # Not modified error code. | ||
| print("\tConditional copy failed: Object not modified") | ||
| else: | ||
| logger.error(f"Unexpected error: {error_code}") | ||
| raise | ||
|
|
||
| # snippet-end:[python.example_code.s3.CopyObjectConditional] | ||
| # snippet-end:[python.example_code.s3.S3ConditionalRequests.wrapper] | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.