Feature Overview
This document provides an overview of APIs and SDK code samples for object deletion.
API | Operation | Description |
Deleting a Single Object | Deletes a specified object from a bucket | |
Deleting Multiple Objects | Deletes multiple objects from a bucket in a single request |
Deleting a Single Object
Note
This API is used to delete a specified object.
Method prototype
delete_object(Bucket, Key, **kwargs)
Sample 1. Deleting an object
# -*- coding=utf-8from qcloud_cos import CosConfigfrom qcloud_cos import CosS3Clientimport sysimport osimport logging# Under normal circumstances, use the INFO log level. To locate issues, change it to DEBUG, and the SDK will print communication information with the server.logging.basicConfig(level=logging.INFO, stream=sys.stdout)# 1. Set user attributes, including secret_id, secret_key, region, etc. Appid has been removed from CosConfig, please include Appid in the Bucket parameter. Bucket is composed of BucketName-Appid.secret_id = os.environ['COS_SECRET_ID'] # User <1>SecretId</1>. We recommend that you use a sub-account key and follow the principle of least privilege to reduce risks. For more information on how to obtain a sub-account key, visit https://cloud.tencent.com/document/product/598/37140.secret_key = os.environ['COS_SECRET_KEY'] # User <1>SecretKey</1>. We recommend that you use a sub-account key and follow the principle of least privilege to reduce risks. For more information on how to obtain a sub-account key, visit https://cloud.tencent.com/document/product/598/37140.region = 'ap-beijing' # Replace it with the actual region, which can be viewed in the console at https://console.cloud.tencent.com/cos5/bucket.For a list of all regions supported by COS, visit https://cloud.tencent.com/document/product/436/6224token = None # Token is required for temporary keys but not permanent keys. For more information about how to generate and use a temporary key, see https://cloud.tencent.com/document/product/436/14048.scheme = 'https' # Specify whether to use HTTP or HTTPS protocol to access COS. This is optional and is https by default.config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token, Scheme=scheme)client = CosS3Client(config)response = client.delete_object(Bucket='examplebucket-1250000000',Key='exampleobject')
Sample 2. Deleting a directory
In COS, a directory is a special object with a path ending in "/". You can directly call the
Delete Object API to delete a directory. Note that only empty directories can be deleted. If you want to delete non-empty directories, see "Deleting objects with a specified prefix".# -*- coding=utf-8from qcloud_cos import CosConfigfrom qcloud_cos import CosS3Clientimport sysimport osimport logging# Under normal circumstances, use the INFO log level. To locate issues, change it to DEBUG, and the SDK will print communication information with the server.logging.basicConfig(level=logging.INFO, stream=sys.stdout)# 1. Set user attributes, including secret_id, secret_key, region, etc. Appid has been removed from CosConfig, please include Appid in the Bucket parameter. Bucket is composed of BucketName-Appid.secret_id = os.environ['COS_SECRET_ID'] # User <1>SecretId</1>. We recommend that you use a sub-account key and follow the principle of least privilege to reduce risks. For more information on how to obtain a sub-account key, visit https://cloud.tencent.com/document/product/598/37140.secret_key = os.environ['COS_SECRET_KEY'] # User <1>SecretKey</1>. We recommend that you use a sub-account key and follow the principle of least privilege to reduce risks. For more information on how to obtain a sub-account key, visit https://cloud.tencent.com/document/product/598/37140.region = 'ap-beijing' # Replace it with the actual region, which can be viewed in the console at https://console.cloud.tencent.com/cos5/bucket.For a list of all regions supported by COS, visit https://cloud.tencent.com/document/product/436/6224token = None # Token is required for temporary keys but not permanent keys. For more information about how to generate and use a temporary key, see https://cloud.tencent.com/document/product/436/14048.scheme = 'https' # Specify whether to use HTTP or HTTPS protocol to access COS. This is optional and is https by default.config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token, Scheme=scheme)client = CosS3Client(config)to_delete_dir='path/to/delete/dir/'response = client.delete_object(Bucket='examplebucket-1250000000',Key=to_delete_dir,)print(response)
Sample 3: Deleting objects with a specified prefix
# -*- coding=utf-8from qcloud_cos import CosConfigfrom qcloud_cos import CosS3Clientimport sysimport osimport logging# Under normal circumstances, use the INFO log level. To locate issues, change it to DEBUG, and the SDK will print communication information with the server.logging.basicConfig(level=logging.INFO, stream=sys.stdout)# Set user attributes, including secret_id, secret_key, region, etc. Appid has been removed from CosConfig, please include Appid in the Bucket parameter. Bucket is composed of BucketName-Appid.secret_id = os.environ['COS_SECRET_ID'] # User <1>SecretId</1>. We recommend that you use a sub-account key and follow the principle of least privilege to reduce risks. For more information on how to obtain a sub-account key, visit https://cloud.tencent.com/document/product/598/37140.secret_key = os.environ['COS_SECRET_KEY'] # User <1>SecretKey</1>. We recommend that you use a sub-account key and follow the principle of least privilege to reduce risks. For more information on how to obtain a sub-account key, visit https://cloud.tencent.com/document/product/598/37140.region = 'ap-beijing' # Replace it with the actual region, which can be viewed in the console at https://console.cloud.tencent.com/cos5/bucket.For a list of all regions supported by COS, visit https://cloud.tencent.com/document/product/436/6224token = None # Token is required for temporary keys but not permanent keys. For more information about how to generate and use a temporary key, see https://cloud.tencent.com/document/product/436/14048.scheme = 'https' # Specify whether to use HTTP or HTTPS protocol to access COS. This is optional and is https by default.config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token, Scheme=scheme)client = CosS3Client(config)# Delete Files with Specified Prefixbucket = 'examplebucket-1250000000'is_over = Falsemarker = ''prefix = 'root/logs'while not is_over:response = client.list_objects(Bucket=bucket, Prefix=prefix, Marker=marker)if 'Contents' in response:for content in response['Contents']:print("delete object: ", content['Key'])client.delete_object(Bucket=bucket, Key=content['Key'])if response['IsTruncated'] == 'false':is_over = Truemarker = response['Marker']
Sample request with all parameters
response = client.delete_object(Bucket='examplebucket-1250000000',Key='exampleobject',VersionId='string',)
Description
Parameter name | ParameterDescription | Local Disk Types | Required |
Bucket | Bucket name in the format of BucketName-APPID | String | Required |
Key | ObjectKey is the unique identifier of the object in the bucket. For example, in the object's access domain name examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/pic.jpg, the ObjectKey is doc/pic.jpg | String | Required |
VersionId | Version ID of the object if versioning is enabled | String | Not required |
Response description
The response contains the information of the deleted object in dict type:
{'x-cos-version-id': 'string','x-cos-delete-marker': 'true'|'false',}
Parameter name | ParameterDescription | Local Disk Types |
x-cos-version-id | Version ID of the deleted object | String |
x-cos-delete-marker | Whether the deleted object is a delete marker | String |
Deleting Multiple Objects
Note
The API (DELETE Multiple Objects) is used to delete multiple objects.
Method prototype
delete_objects(Bucket, Delete={}, **kwargs)
Sample Request
# -*- coding=utf-8from qcloud_cos import CosConfigfrom qcloud_cos import CosS3Clientimport sysimport osimport logging# Under normal circumstances, use the INFO log level. To locate issues, change it to DEBUG, and the SDK will print communication information with the server.logging.basicConfig(level=logging.INFO, stream=sys.stdout)# 1. Set user attributes, including secret_id, secret_key, region, etc. Appid has been removed from CosConfig, please include Appid in the Bucket parameter. Bucket is composed of BucketName-Appid.secret_id = os.environ['COS_SECRET_ID'] # User <1>SecretId</1>. We recommend that you use a sub-account key and follow the principle of least privilege to reduce risks. For more information on how to obtain a sub-account key, visit https://cloud.tencent.com/document/product/598/37140.secret_key = os.environ['COS_SECRET_KEY'] # User <1>SecretKey</1>. We recommend that you use a sub-account key and follow the principle of least privilege to reduce risks. For more information on how to obtain a sub-account key, visit https://cloud.tencent.com/document/product/598/37140.region = 'ap-beijing' # Replace it with the actual region, which can be viewed in the console at https://console.cloud.tencent.com/cos5/bucket.For a list of all regions supported by COS, visit https://cloud.tencent.com/document/product/436/6224token = None # Token is required for temporary keys but not permanent keys. For more information about how to generate and use a temporary key, see https://cloud.tencent.com/document/product/436/14048.scheme = 'https' # Specify whether to use HTTP or HTTPS protocol to access COS. This is optional and is https by default.config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token, Scheme=scheme)client = CosS3Client(config)response = client.delete_objects(Bucket='examplebucket-1250000000',Delete={'Object': [{'Key': 'exampleobject1'},{'Key': 'exampleobject2'}]})
Sample request with all parameters
response = client.delete_objects(Bucket='examplebucket-1250000000',Delete={'Object': [{'Key': 'exampleobject1','VersionId': 'string'},{'Key': 'exampleobject2','VersionId': 'string'},],'Quiet': 'true'|'false'})
Description
Parameter name | ParameterDescription | Local Disk Types | Required |
Bucket | Bucket name in the format of BucketName-APPID | String | Required |
Delete | Indicates how to return the deletion results and the target object | Dict | Required |
Object | Describes information on each object to be deleted | List | Required |
Key | ObjectKey is the unique identifier of the object in the bucket. For example, in the object's access domain name examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/pic.jpg, the ObjectKey is doc/pic.jpg | String | Not required |
VersionId | Version IDs of the objects to be deleted if versioning is enabled. | String | Not required |
Quiet | Specifies how the deletion results are returned. Valid values: true: returns only the failed results. false (default): returns all results. | String | Not required |
Response description
This response contains the deletion results in dict format:
{'Deleted': [{'Key': 'string','VersionId': 'string','DeleteMarker': 'true'|'false','DeleteMarkerVersionId': 'string'},{'Key': 'string',},],'Error': [{'Key': 'string','VersionId': 'string','Code': 'string','Message': 'string'},]}
Parameter name | ParameterDescription | Local Disk Types |
Deleted | Information on the successfully deleted objects | List |
Key | Paths to the successfully deleted objects | String |
VersionId | Version IDs of the successfully deleted objects | String |
DeleteMarker | Identifies whether the successfully deleted object is a delete marker | String |
DeleteMarkerVersionId | Version IDs of the delete markers of the successfully deleted objects | String |
Error | Information on objects that fail to be deleted | List |
Key | Paths to the objects that failed to be deleted | String |
VersionId | Version IDs of the objects that failed to be deleted | String |
Code | Error code for objects that fail to be deleted | String |
Message | The error message for objects that failed to be deleted | String |
Deleting multiple objects (deleting a directory)
Note
Object storage itself does not have the concept of directories. To accommodate user habits, you can use the delimiter
/ to simulate "directories."In COS, deleting a directory and the objects contained actually means deleting objects that have the same specified prefix. Currently, COS’s Python SDK does not provide a standalone API to perform this operation. However, you can still do so with a combination of basic operations (query object list + batch delete objects).
Sample Request
# -*- coding=utf-8from qcloud_cos import CosConfigfrom qcloud_cos import CosS3Clientfrom qcloud_cos.cos_threadpool import SimpleThreadPoolimport osimport sysimport osimport logging# Under normal circumstances, use the INFO log level. To locate issues, change it to DEBUG, and the SDK will print communication information with the server.logging.basicConfig(level=logging.INFO, stream=sys.stdout)# 1. Set user attributes, including secret_id, secret_key, region, etc. Appid has been removed from CosConfig, please include Appid in the Bucket parameter. Bucket is composed of BucketName-Appid.secret_id = os.environ['COS_SECRET_ID'] # User <1>SecretId</1>. We recommend that you use a sub-account key and follow the principle of least privilege to reduce risks. For more information on how to obtain a sub-account key, visit https://cloud.tencent.com/document/product/598/37140.secret_key = os.environ['COS_SECRET_KEY'] # User <1>SecretKey</1>. We recommend that you use a sub-account key and follow the principle of least privilege to reduce risks. For more information on how to obtain a sub-account key, visit https://cloud.tencent.com/document/product/598/37140.region = 'ap-beijing' # Replace it with the actual region, which can be viewed in the console at https://console.cloud.tencent.com/cos5/bucket.For a list of all regions supported by COS, visit https://cloud.tencent.com/document/product/436/6224token = None # Token is required for temporary keys but not permanent keys. For more information about how to generate and use a temporary key, see https://cloud.tencent.com/document/product/436/14048.scheme = 'https' # Specify whether to use HTTP or HTTPS protocol to access COS. This is optional and is https by default.config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token, Scheme=scheme)client = CosS3Client(config)bucket = 'examplebucket-1250000000'folder = 'folder/' # A directory to delete (an object name ending with a slash (/) is a directory)def delete_cos_dir():pool = SimpleThreadPool()marker = ""while True:file_infos = []# List 100 objects per pageresponse = client.list_objects(Bucket=bucket, Prefix=folder, Marker=marker, MaxKeys=100)if "Contents" in response:contents = response.get("Contents")file_infos.extend(contents)pool.add_task(delete_files, file_infos)# Listing completed, exitif response['IsTruncated'] == 'false':breakListing the Next Pagemarker = response["NextMarker"]pool.wait_completion()return Nonedef delete_files(file_infos):Constructing a Batch Deletion Requestdelete_list = []for file in file_infos:delete_list.append({"Key": file['Key']})response = client.delete_objects(Bucket=bucket, Delete={"Object": delete_list})print(response)if __name__ == "__main__":delete_cos_dir()