列举存储空间(Python SDK V1)

存储空间(Bucket)是用来存储对象(Object)的容器。对象都隶属于存储空间。存储空间按照字母顺序排列。您可以列举当前账号所有地域下符合指定条件的存储空间。

注意事项

列举所有存储空间

以下代码用于列举当前账号所有地域下的存储空间。

说明

以下代码不支持列举指定地域的存储空间。例如,您在代码中填写的Bucket所在地域为华东1(杭州),则依然会列举您的阿里云账号下所有地域的存储空间。

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# 填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"

# 填写Endpoint对应的Region信息,例如cn-hangzhou。注意,v4签名下,必须填写该参数
region = "cn-hangzhou"

service = oss2.Service(auth, endpoint, region=region)

# 列举当前账号所有地域下的存储空间。
for b in oss2.BucketIterator(service):
    print(b.name)

列举指定前缀的存储空间

以下代码用于列举当前账号所有地域下以example为前缀(prefix)的存储空间。

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# 填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"

# 填写Endpoint对应的Region信息,例如cn-hangzhou。注意,v4签名下,必须填写该参数
region = "cn-hangzhou"

service = oss2.Service(auth, endpoint, region=region)

# 列举当前账号所有地域下前缀为example的存储空间。
for b in oss2.BucketIterator(service, prefix='example'):
    print(b.name)

列举指定marker之后的存储空间

以下代码用于列举当前账号所有地域下名称的字母序排在examplebucket之后的存储空间。

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# 填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"

# 填写Endpoint对应的Region信息,例如cn-hangzhou。注意,v4签名下,必须填写该参数
region = "cn-hangzhou"

service = oss2.Service(auth, endpoint, region=region)

# 列举当前账号所有地域下名称的字母序排在examplebucket之后的存储空间。列举结果中不包含名为examplebucket的存储空间。
for b in oss2.BucketIterator(service, marker='examplebucket'):
    print(b.name)

相关文档