有奖捉虫:云通信与企业服务文档专题,速来> HOT

简介

本文档提供关于删除操作相关的 API 概览以及 SDK 示例代码。
API
操作名
操作描述
删除单个对象
在存储桶中删除指定对象
删除多个对象
在存储桶中批量删除指定对象

删除单个对象

功能说明

删除指定的对象(DELETE Object)。

方法原型

delete_object(Bucket, Key, **kwargs)

请求示例1:删除单个对象

# -*- coding=utf-8
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys
import os
import logging

# 正常情况日志级别使用 INFO,需要定位时可以修改为 DEBUG,此时 SDK 会打印和服务端的通信信息
logging.basicConfig(level=logging.INFO, stream=sys.stdout)

# 1. 设置用户属性, 包括 secret_id, secret_key, region等。Appid 已在 CosConfig 中移除,请在参数 Bucket 中带上 Appid。Bucket 由 BucketName-Appid 组成
secret_id = os.environ['COS_SECRET_ID'] # 用户的 SecretId,建议使用子账号密钥,授权遵循最小权限指引,降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
secret_key = os.environ['COS_SECRET_KEY'] # 用户的 SecretKey,建议使用子账号密钥,授权遵循最小权限指引,降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
region = 'ap-beijing' # 替换为用户的 region,已创建桶归属的 region 可以在控制台查看,https://console.cloud.tencent.com/cos5/bucket
# COS 支持的所有 region 列表参见 https://cloud.tencent.com/document/product/436/6224
token = None # 如果使用永久密钥不需要填入 token,如果使用临时密钥需要填入,临时密钥生成和使用指引参见 https://cloud.tencent.com/document/product/436/14048
scheme = 'https' # 指定使用 http/https 协议来访问 COS,默认为 https,可不填

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'
)

请求示例2:删除目录

对象存储中,目录是特殊的路径以“/”结尾的 object。可直接调用 Delete Object 接口实现删除目录。注意,仅支持删除空目录,如果要删除非空目录,请参考“前缀批量删除”。
# -*- coding=utf-8
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys
import os
import logging

# 正常情况日志级别使用 INFO,需要定位时可以修改为 DEBUG,此时 SDK 会打印和服务端的通信信息
logging.basicConfig(level=logging.INFO, stream=sys.stdout)

# 1. 设置用户属性, 包括 secret_id, secret_key, region等。Appid 已在 CosConfig 中移除,请在参数 Bucket 中带上 Appid。Bucket 由 BucketName-Appid 组成
secret_id = os.environ['COS_SECRET_ID'] # 用户的 SecretId,建议使用子账号密钥,授权遵循最小权限指引,降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
secret_key = os.environ['COS_SECRET_KEY'] # 用户的 SecretKey,建议使用子账号密钥,授权遵循最小权限指引,降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
region = 'ap-beijing' # 替换为用户的 region,已创建桶归属的region可以在控制台查看,https://console.cloud.tencent.com/cos5/bucket
# COS 支持的所有 region 列表参见 https://cloud.tencent.com/document/product/436/6224
token = None # 如果使用永久密钥不需要填入 token,如果使用临时密钥需要填入,临时密钥生成和使用指引参见 https://cloud.tencent.com/document/product/436/14048
scheme = 'https' # 指定使用 http/https 协议来访问 COS,默认为 https,可不填

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)

请求示例3:前缀批量删除

# -*- coding=utf-8
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client

import sys
import os
import logging

# 正常情况日志级别使用 INFO,需要定位时可以修改为 DEBUG,此时 SDK 会打印和服务端的通信信息
logging.basicConfig(level=logging.INFO, stream=sys.stdout)

# 设置用户属性, 包括 secret_id, secret_key, region等。Appid 已在 CosConfig 中移除,请在参数 Bucket 中带上 Appid。Bucket 由 BucketName-Appid 组成
secret_id = os.environ['COS_SECRET_ID'] # 用户的 SecretId,建议使用子账号密钥,授权遵循最小权限指引,降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
secret_key = os.environ['COS_SECRET_KEY'] # 用户的 SecretKey,建议使用子账号密钥,授权遵循最小权限指引,降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
region = 'ap-beijing' # 替换为用户的 region,已创建桶归属的 region 可以在控制台查看,https://console.cloud.tencent.com/cos5/bucket
# COS 支持的所有 region 列表参见 https://cloud.tencent.com/document/product/436/6224
token = None # 如果使用永久密钥不需要填入 token,如果使用临时密钥需要填入,临时密钥生成和使用指引参见 https://cloud.tencent.com/document/product/436/14048
scheme = 'https' # 指定使用 http/https 协议来访问 COS,默认为 https,可不填

config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token, Scheme=scheme)
client = CosS3Client(config)

# 删除指定前缀 (prefix)的文件
bucket = 'examplebucket-1250000000'
marker = ''
prefix = 'root/logs'
while True:
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':
break

marker = response['NextMarker']

全部参数请求示例

response = client.delete_object(
Bucket='examplebucket-1250000000',
Key='exampleobject',
VersionId='string'
)

参数说明

参数名称
参数描述
类型
是否必填
Bucket
存储桶名称,由 BucketName-APPID 构成
String
Key
对象键(Key)是对象在存储桶中的唯一标识。例如,在对象的访问域名 examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/pic.jpg 中,对象键为 doc/pic.jpg
String
VersionId
开启版本控制后,指定对象的具体版本
String

返回结果说明

删除对象的信息,类型为 dict:
{
'x-cos-version-id': 'string',
'x-cos-delete-marker': 'true'|'false'
}
参数名称
参数描述
类型
x-cos-version-id
删除对象的版本号
String
x-cos-delete-marker
标识删除的对象是否为 delete marker
String

删除多个对象

功能说明

删除多个指定的对象(DELETE Multiple Objects)。

方法原型

delete_objects(Bucket, Delete={}, **kwargs)

请求示例

# -*- coding=utf-8
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys
import os
import logging

# 正常情况日志级别使用 INFO,需要定位时可以修改为 DEBUG,此时 SDK 会打印和服务端的通信信息
logging.basicConfig(level=logging.INFO, stream=sys.stdout)

# 1. 设置用户属性, 包括 secret_id, secret_key, region 等。Appid 已在 CosConfig 中移除,请在参数 Bucket 中带上 Appid。Bucket 由 BucketName-Appid 组成
secret_id = os.environ['COS_SECRET_ID'] # 用户的 SecretId,建议使用子账号密钥,授权遵循最小权限指引,降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
secret_key = os.environ['COS_SECRET_KEY'] # 用户的 SecretKey,建议使用子账号密钥,授权遵循最小权限指引,降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
region = 'ap-beijing' # 替换为用户的 region,已创建桶归属的 region 可以在控制台查看,https://console.cloud.tencent.com/cos5/bucket
# COS 支持的所有 region 列表参见 https://cloud.tencent.com/document/product/436/6224
token = None # 如果使用永久密钥不需要填入 token,如果使用临时密钥需要填入,临时密钥生成和使用指引参见 https://cloud.tencent.com/document/product/436/14048
scheme = 'https' # 指定使用 http/https 协议来访问 COS,默认为 https,可不填

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'
}
]
}
)

全部参数请求示例

response = client.delete_objects(
Bucket='examplebucket-1250000000',
Delete={
'Object': [
{
'Key': 'exampleobject1',
'VersionId': 'string'
},
{
'Key': 'exampleobject2',
'VersionId': 'string'
},
],
'Quiet': 'true'|'false'
}
)

参数说明

参数名称
参数描述
类型
是否必填
Bucket
Bucket 名称,由 BucketName-APPID 构成
String
Delete
说明本次删除的返回结果方式和目标 Object
Dict
Object
说明每个将要删除的目标 Object 信息
List
Key
对象键(Key)是对象在存储桶中的唯一标识。例如,在对象的访问域名 examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/pic.jpg 中,对象键为 doc/pic.jpg
String
VersionId
开启版本控制后,目的对象的版本号
String
Quiet
指明删除的返回结果方式,可选值为 true、false,默认为 false。设置为 true 只返回失败的错误信息,设置为 false 时返回成功和失败的所有信息
String

返回结果说明

批量删除对象的结果,类型为 dict:
{
'Deleted': [
{
'Key': 'string',
'VersionId': 'string',
'DeleteMarker': 'true'|'false',
'DeleteMarkerVersionId': 'string'
},
{
'Key': 'string',
},
],
'Error': [
{
'Key': 'string',
'VersionId': 'string',
'Code': 'string',
'Message': 'string'
},
]
}
参数名称
参数描述
类型
Deleted
删除成功的 Object 信息
List
Key
删除成功的 Object 的路径
String
VersionId
删除成功的 Object 的版本号
String
DeleteMarker
删除成功的 Object 是否为 delete marker
String
DeleteMarkerVersionId
删除成功的 Object 的 delete marker 的版本号
String
Error
删除失败的 Object 信息
List
Key
删除失败的 Object 的路径
String
VersionId
删除失败的 Object 的版本号
String
Code
删除失败的 Object 对应的错误码
String
Message
删除失败的 Object 对应的错误信息
String

批量删除对象(删除目录)

功能说明

对象存储中本身是没有目录的概念的,为了满足用户使用习惯,用户可通过分隔符/来模拟“目录”。
删除目录及其文件这一场景,实际在 COS 上相当于删除一批有着同样前缀的对象。目前 COS Python SDK 没有提供一个接口去实现这样的操作,但是可以通过组合查询对象列表加上批量删除对象的基本操作,达到删除目录及其文件的效果。

请求示例

# -*- coding=utf-8
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
from qcloud_cos.cos_threadpool import SimpleThreadPool
import os
import sys
import os
import logging

# 正常情况日志级别使用 INFO,需要定位时可以修改为 DEBUG,此时 SDK 会打印和服务端的通信信息
logging.basicConfig(level=logging.INFO, stream=sys.stdout)

# 1. 设置用户属性, 包括 secret_id, secret_key, region等。Appid 已在CosConfig中移除,请在参数 Bucket 中带上 Appid。Bucket 由 BucketName-Appid 组成
secret_id = os.environ['COS_SECRET_ID'] # 用户的 SecretId,建议使用子账号密钥,授权遵循最小权限指引,降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
secret_key = os.environ['COS_SECRET_KEY'] # 用户的 SecretKey,建议使用子账号密钥,授权遵循最小权限指引,降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
region = 'ap-beijing' # 替换为用户的 region,已创建桶归属的 region 可以在控制台查看,https://console.cloud.tencent.com/cos5/bucket
# COS 支持的所有 region 列表参见 https://cloud.tencent.com/document/product/436/6224
token = None # 如果使用永久密钥不需要填入 token,如果使用临时密钥需要填入,临时密钥生成和使用指引参见 https://cloud.tencent.com/document/product/436/14048
scheme = 'https' # 指定使用 http/https 协议来访问 COS,默认为 https,可不填

config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token, Scheme=scheme)
client = CosS3Client(config)

bucket = 'examplebucket-1250000000'
folder = 'folder/' # 要删除的目录,'/'结尾表示目录

def delete_cos_dir():
pool = SimpleThreadPool()
marker = ""
while True:
file_infos = []

# 列举一页100个对象
response = 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)

# 列举完成,退出
if response['IsTruncated'] == 'false':
break

# 列举下一页
marker = response["NextMarker"]

pool.wait_completion()
return None

def delete_files(file_infos):

# 构造批量删除请求
delete_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()