Este tema describe cómo listar los objetos de un bucket con control de versiones. Puede listar todos los objetos, una cantidad específica o aquellos cuyos nombres contienen un prefijo determinado.
Notas
En este tema se utiliza el endpoint público de la región China (Hangzhou). Si desea acceder a OSS desde otros servicios de Alibaba Cloud en la misma región que OSS, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.
En este tema, las credenciales de acceso se obtienen de variables de entorno. Para obtener más información sobre cómo configurar las credenciales de acceso, consulte Configure access credentials using OSS SDK for Python 1.0.
Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para conocer configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Initialization.
Para listar objetos, debe contar con el permiso
oss:ListObjectVersions. Para obtener más información, consulte Grant a custom policy.
Listar las versiones de todos los objetos de un bucket
A continuación se muestra un ejemplo de código para listar las versiones de todos los objetos, incluidos los marcadores de eliminación, en un bucket específico:
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"
# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)
# Call the list_object_versions operation to list the versions of objects in a versioning-enabled bucket.
# List the versions of all objects, including delete markers in the bucket.
result = bucket.list_object_versions()
# List the versions of all objects in the bucket.
next_key_marker = None
next_versionid_marker = None
while True:
result = bucket.list_object_versions(key_marker=next_key_marker, versionid_marker=next_versionid_marker)
# Display the versions of the listed objects.
for version_info in result.versions:
print('version_info.versionid:', version_info.versionid)
print('version_info.key:', version_info.key)
print('version_info.is_latest:', version_info.is_latest)
# Display the versions of the listed delete markers.
for del_maker_Info in result.delete_marker:
print('del_maker.key:', del_maker_Info.key)
print('del_maker.versionid:', del_maker_Info.versionid)
print('del_maker.is_latest:', del_maker_Info.is_latest)
is_truncated = result.is_truncated
# Check whether all versions of all objects in the bucket are listed. If the versions of all objects are incompletely listed, the list operation continues. If the versions of all objects are completely listed, the list operation stops.
if is_truncated:
next_key_marker = result.next_key_marker
next_versionid_marker = result.next_versionid_marker
else:
break
Listar las versiones de objetos cuyos nombres contienen un prefijo específico
A continuación se muestra un ejemplo de código para listar las versiones de los objetos cuyos nombres contienen un prefijo determinado:
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"
# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)
# Call the list_object_versions operation to list the versions of objects in a versioning-enabled bucket.
# List the versions of all objects, including delete markers in the bucket.
result = bucket.list_object_versions()
# List the versions of objects whose names contain the test- prefix.
prefix = 'test-'
next_key_marker = None
next_versionid_marker = None
while True:
result = bucket.list_object_versions(prefix=prefix, key_marker=next_key_marker, versionid_marker=next_versionid_marker)
# Display the versions of the listed objects.
for version_info in result.versions:
print('version_info.versionid:', version_info.versionid)
print('version_info.key:', version_info.key)
print('version_info.is_latest:', version_info.is_latest)
# Display the versions of the listed delete markers.
for del_maker_Info in result.delete_marker:
print('del_maker.key:', del_maker_Info.key)
print('del_maker.versionid:', del_maker_Info.versionid)
print('del_maker.is_latest:', del_maker_Info.is_latest)
is_truncated = result.is_truncated
# Check whether all versions of all objects in the bucket are listed. If the versions of all objects are incompletely listed, the list operation continues. If the versions of all objects are completely listed, the list operation stops.
if is_truncated:
next_key_marker = result.next_key_marker
next_versionid_marker = result.next_versionid_marker
else:
break
Listar las versiones de una cantidad específica de objetos
A continuación se muestra un ejemplo de código para listar las versiones de una cantidad determinada de objetos:
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"
# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)
# Call the list_object_versions operation to list the versions of objects in a versioning-enabled bucket.
# List the versions of all objects, including delete markers in the bucket.
result = bucket.list_object_versions()
# List up to 200 object versions.
max_keys = 200
result = bucket.list_object_versions(max_keys=max_keys)
# Display the versions of the listed objects.
for version_info in result.versions:
print('version_info.versionid:', version_info.versionid)
print('version_info.key:', version_info.key)
print('version_info.is_latest:', version_info.is_latest)
# Display the versions of the listed delete markers.
for del_maker_Info in result.delete_marker:
print('del_maker.key:', del_maker_Info.key)
print('del_maker.versionid:', del_maker_Info.versionid)
print('del_maker.is_latest:', del_maker_Info.is_latest)
# Check whether the listing is truncated.
# If the number of objects in the bucket is greater than 200, the value of is_truncated is True, which indicates that the listing is truncated. If the number of objects in the bucket is smaller than 200, the value of is_truncated is False, which indicates that the listing is not truncated.
print('is truncated', result.is_truncated)
Listar objetos por directorio
OSS utiliza una estructura plana para almacenar objetos. Un directorio es un objeto de cero bytes cuyo nombre termina con una barra diagonal (/). Es posible cargar y descargar un directorio. De forma predeterminada, un objeto cuyo nombre termina con una barra diagonal (/) se muestra como un directorio en la consola de OSS.
Para listar objetos por directorio, especifique los parámetros delimiter y prefix en la solicitud.
Si establece
prefixcon el nombre de un directorio en la solicitud, se listan los objetos y subdirectorios cuyos nombres contienen ese prefijo.Si especifica un prefijo y establece
delimitercon una barra diagonal (/) en la solicitud, se listan los objetos y subdirectorios cuyos nombres comienzan con dicho prefijo dentro del directorio. Cada subdirectorio aparece como un único elemento de resultado enCommonPrefixes. Los objetos y directorios contenidos en esos subdirectorios no se listan.
Por ejemplo, suponga que un bucket llamado examplebucket contiene los siguientes objetos: oss.jpg, fun/test.jpg, fun/movie/001.avi y fun/movie/007.txt. La barra diagonal (/) se usa como delimitador del directorio. La siguiente estructura muestra los objetos y directorios del bucket examplebucket.
examplebucket
└── oss.jpg
└── fun
└── test.jpg
└── movie
└── 001.avi
└── 007.txt
Los siguientes ejemplos describen cómo listar objetos en directorios simulados.
-
Listar las versiones de los objetos dentro del directorio raíz de un bucket
A continuación se muestra un ejemplo de código para listar las versiones de los objetos en el directorio raíz de un bucket:
# -*- coding: utf-8 -*- import oss2 from oss2.credentials import EnvironmentVariableCredentialsProvider # Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider()) # Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. endpoint = "https://oss-cn-hangzhou.aliyuncs.com" # Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4. region = "cn-hangzhou" # Specify the name of your bucket. bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region) # Call the list_object_versions operation to list the versions of objects in a versioning-enabled bucket. # List the versions of all objects, including delete markers in the bucket. result = bucket.list_object_versions() # Specify the forward slash (/) as the delimiter. delimiter = "/" next_key_marker = None next_versionid_marker = None while True: result = bucket.list_object_versions(delimiter=delimiter, key_marker=next_key_marker, versionid_marker=next_versionid_marker) # Display the versions of the listed objects. for version_info in result.versions: print('version_info.versionid:', version_info.versionid) print('version_info.key:', version_info.key) print('version_info.is_latest:', version_info.is_latest) # Display the versions of the listed delete markers. for del_maker_Info in result.delete_marker: print('del_maker.key:', del_maker_Info.key) print('del_maker.versionid:', del_maker_Info.versionid) print('del_maker.is_latest:', del_maker_Info.is_latest) # Display the directories whose names end with a forward slash (/). for common_prefix in result.common_prefix: print("common_prefix:", common_prefix) is_truncated = result.is_truncated # Check whether all versions of all objects in the bucket are listed. If the versions of all objects are incompletely listed, the list operation continues. If the versions of all objects are completely listed, the list operation stops. if is_truncated: next_key_marker = result.next_key_marker next_versionid_marker = result.next_versionid_marker else: breakResultado
('version_info.versionid:', 'CAEQEhiBgMCw8Y7FqBciIGIzMDE3MTEzOWRiMDRmZmFhMmRlMjljZWI0MWU4****') ('version_info.key:', 'oss.jpg') ('version_info.is_latest:', True) ('common_prefix:', 'fun/') -
Listar los objetos y subdirectorios de un directorio específico
A continuación se muestra un ejemplo de código para listar los objetos y subdirectorios dentro de un directorio de un bucket:
# -*- coding: utf-8 -*- import oss2 from oss2.credentials import EnvironmentVariableCredentialsProvider # Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider()) # Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. endpoint = "https://oss-cn-hangzhou.aliyuncs.com" # Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4. region = "cn-hangzhou" # Specify the name of your bucket. bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region) # Call the list_object_versions operation to list the versions of objects in a versioning-enabled bucket. # List the versions of all objects including delete markers in a bucket. result = bucket.list_object_versions() # Set delimiter to a forward slash (/) and prefix to fun/. prefix = "fun/" delimiter = "/" next_key_marker = None next_versionid_marker = None while True: result = bucket.list_object_versions(prefix=prefix, delimiter=delimiter, key_marker=next_key_marker, versionid_marker=next_versionid_marker) # Display the versions of the listed objects. for version_info in result.versions: print('version_info.versionid:', version_info.versionid) print('version_info.key:', version_info.key) print('version_info.is_latest:', version_info.is_latest) # Display the versions of the listed delete markers. for del_maker_Info in result.delete_marker: print('del_maker.key:', del_maker_Info.key) print('del_maker.versionid:', del_maker_Info.versionid) print('del_maker.is_latest:', del_maker_Info.is_latest) # Display the directories whose names end with a forward slash (/). for common_prefix in result.common_prefix: print("common_prefix:", common_prefix) is_truncated = result.is_truncated # Check whether all versions of all objects in the bucket are listed. If the versions of all objects are incompletely listed, the list operation continues. If the versions of all objects are completely listed, the list operation stops. if is_truncated: next_key_marker = result.next_key_marker next_versionid_marker = result.next_versionid_marker else: breakResultado
('version_info.versionid:', 'CAEQFRiBgMCh9JDkrxciIGE3OTNkYzFhYTc2YzQzOTQ4Y2MzYjg2YjQ4ODg*****') ('version_info.key:', 'fun/test.jpg') ('version_info.is_latest:', True) ('commonPrefix:', 'fun/movie/')
Referencias
Para obtener más información sobre la operación de API que permite listar objetos, consulte ListObjectVersions (GetBucketVersions).