El SDK de Object Storage Service (OSS) para Python proporciona iteradores encapsulados para listar objetos en un bucket. Estos iteradores permiten filtrar objetos por prefijo, posición inicial y otros criterios.
Uso
El SDK de OSS para Python ofrece dos iteradores para listar objetos: ObjectIterator, basado en la operación GetBucket (ListObjects), y ObjectIteratorV2, basado en la operación ListObjectsV2 (GetBucketV2). Las principales diferencias son:
ObjectIterator: Devuelve la información del propietario de forma predeterminada.-
ObjectIteratorV2: Utiliza el parámetrofetch_ownerpara especificar si se debe devolver la información del propietario.El uso de
ObjectIteratorV2requiere la versión 2.12.0 o posterior del SDK de OSS para Python.
Se recomienda ObjectIteratorV2 por su compatibilidad mejorada con buckets que tienen habilitado el control de versiones.
-
ObjectIteratorV2constructoross2.ObjectIteratorV2(bucket, prefix='', delimiter='', continuation_token='', start_after='', fetch_owner=False, encoding_type = 'url', max_keys=100, max_retries=None, headers=None) -
ObjectIteratorconstructoross2.ObjectIterator(bucket, prefix='', delimiter='', marker='', max_keys=100, max_retries=None, headers=None)
Ejemplos de código
Antes de ejecutar el código, instale el SDK de OSS para Python y configure las variables de entorno para las credenciales de acceso. Para obtener más información, consulte Quick start with OSS SDK for Python. Una cuenta de Alibaba Cloud tiene todos los permisos de forma predeterminada. Si utiliza un usuario de Resource Access Management (RAM) o un rol de RAM, asegúrese de que el usuario o rol cuente con el permiso oss:ListObjects.
Listar todos los objetos
ObjectIteratorV2 (Recommended)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
def main():
# Get access credentials from environment variables.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Set the endpoint and region where the bucket is located.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
region = "cn-hangzhou"
# Initialize the bucket.
bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)
# List all objects in the bucket.
print("List all objects:")
for obj in oss2.ObjectIteratorV2(bucket):
print(f"Object name: {obj.key}, Size: {obj.size} bytes")
if __name__ == "__main__":
main()
Para recuperar la información del propietario de los objetos, establezca fetch_owner=True.
# List all objects and get their owner information.
for obj in oss2.ObjectIteratorV2(bucket, fetch_owner=True):
print(f"Object name: {obj.key}")
print(f"Owner name: {obj.owner.display_name}")
print(f"Owner ID: {obj.owner.id}")
ObjectIterator
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
def main():
# Get access credentials from environment variables.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Set the endpoint and region where the bucket is located.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
region = "cn-hangzhou"
# Initialize the bucket.
bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)
# List all objects in the bucket.
print("List all objects:")
for obj in oss2.ObjectIterator(bucket):
print(f"Object name: {obj.key}, Size: {obj.size} bytes")
if __name__ == "__main__":
main()
Listar un número específico de objetos
ObjectIteratorV2 (Recommended)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from itertools import islice
def main():
# Get access credentials from environment variables.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Set the endpoint and region where the bucket is located.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
region = "cn-hangzhou"
# Initialize the bucket.
bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)
# List the first 10 objects in the bucket.
print("List the first 10 objects:")
for obj in islice(oss2.ObjectIteratorV2(bucket), 10):
print(f"Object name: {obj.key}")
if __name__ == "__main__":
main()
ObjectIterator
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from itertools import islice
def main():
# Get access credentials from environment variables.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Set the endpoint and region where the bucket is located.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
region = "cn-hangzhou"
# Initialize the bucket.
bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)
# List the first 10 objects in the bucket.
print("List the first 10 objects:")
for obj in islice(oss2.ObjectIterator(bucket), 10):
print(f"Object name: {obj.key}")
if __name__ == "__main__":
main()
Listar objetos con un prefijo específico
Suponga que un bucket contiene cuatro objetos: oss.jpg, fun/test.jpg, fun/movie/001.avi y fun/movie/007.avi. La barra diagonal (/) se utiliza como separador de carpetas.
ObjectIteratorV2 (Recommended)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
def main():
# Get access credentials from environment variables.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Set the endpoint and region where the bucket is located.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
region = "cn-hangzhou"
# Initialize the bucket.
bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)
# List all objects in the fun folder, including objects in its subdirectories.
print("List all objects with the prefix fun/:")
for obj in oss2.ObjectIteratorV2(bucket, prefix='fun/'):
print(f"Object name: {obj.key}")
if __name__ == "__main__":
main()
Salida esperada:
List all objects with the prefix fun/:
Object name: fun/
Object name: fun/movie/
Object name: fun/movie/001.avi
Object name: fun/movie/007.avi
Object name: fun/test.jpg
ObjectIterator
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
def main():
# Get access credentials from environment variables.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Set the endpoint and region where the bucket is located.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
region = "cn-hangzhou"
# Initialize the bucket.
bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)
# List all objects in the fun folder, including objects in its subdirectories.
print("List all objects with the prefix fun/:")
for obj in oss2.ObjectIterator(bucket, prefix='fun/'):
print(f"Object name: {obj.key}")
if __name__ == "__main__":
main()
Salida esperada:
List all objects with the prefix fun/:
Object name: fun/
Object name: fun/movie/
Object name: fun/movie/001.avi
Object name: fun/movie/007.avi
Object name: fun/test.jpg
Listar objetos y subdirectorios en un directorio específico
OSS no tiene el concepto de carpetas; todos los elementos se almacenan como objetos. Para crear una carpeta, puede crear un objeto de cero bytes que termine con una barra diagonal (/). La consola de OSS muestra los objetos que terminan con una barra diagonal (/) como carpetas.
Puede utilizar los parámetros delimiter y prefix para simular la funcionalidad de carpetas.
Si establece
prefixcon el nombre de una carpeta, la operación lista todos los objetos cuyas claves comienzan con este prefijo. Esto enumera recursivamente todo el contenido de la carpeta simulada.Si además establece
delimitercomo una barra diagonal (/), la operación lista únicamente los objetos y los nombres de subdirectorios en el nivel superior de dicha carpeta. Los objetos ubicados dentro de los subdirectorios no se listan.
ObjectIteratorV2 (Recommended)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
def main():
# Get access credentials from environment variables.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Set the endpoint and region where the bucket is located.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
region = "cn-hangzhou"
# Initialize the bucket.
bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)
# List the objects and subfolder names in the fun folder, but not the objects within the subfolders.
print("List objects and subdirectories in the fun directory:")
for obj in oss2.ObjectIteratorV2(bucket, prefix='fun/', delimiter='/', start_after='fun/'):
# Use the is_prefix method to determine whether the obj is a folder.
if obj.is_prefix():
print(f"Subdirectory: {obj.key}")
else:
print(f"Object: {obj.key}")
if __name__ == "__main__":
main()
Salida esperada:
List objects and subdirectories in the fun directory:
Subdirectory: fun/movie/
Object: fun/test.jpg
ObjectIterator
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
def main():
# Get access credentials from environment variables.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Set the endpoint and region where the bucket is located.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
region = "cn-hangzhou"
# Initialize the bucket.
bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)
# List the objects and subfolder names in the fun folder, but not the objects within the subfolders.
print("List objects and subdirectories in the fun directory:")
for obj in oss2.ObjectIterator(bucket, prefix='fun/', delimiter='/', marker='fun/'):
# Use the is_prefix method to determine whether the obj is a folder.
if obj.is_prefix():
print(f"Subdirectory: {obj.key}")
else:
print(f"Object: {obj.key}")
if __name__ == "__main__":
main()
Salida esperada:
List objects and subdirectories in the fun directory:
Subdirectory: fun/movie/
Object: fun/test.jpg
Listar objetos después de una posición de inicio específica
Suponga que un bucket contiene los siguientes cuatro objetos: x1.txt, x2.txt, z1.txt y z2.txt.
ObjectIteratorV2 (Recommended)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
def main():
# Get access credentials from environment variables.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Set the endpoint and region where the bucket is located.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
region = "cn-hangzhou"
# Initialize the bucket.
bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)
# List all objects after x2.txt (excluding x2.txt itself).
print("List all objects after x2.txt:")
for obj in oss2.ObjectIteratorV2(bucket, start_after="x2.txt"):
print(f"Object name: {obj.key}")
if __name__ == "__main__":
main()
Salida esperada:
List all objects after x2.txt:
Object name: z1.txt
Object name: z2.txt
ObjectIterator
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
def main():
# Get access credentials from environment variables.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Set the endpoint and region where the bucket is located.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
region = "cn-hangzhou"
# Initialize the bucket.
bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)
# List all objects after x2.txt (excluding x2.txt itself).
print("List all objects after x2.txt:")
for obj in oss2.ObjectIterator(bucket, marker="x2.txt"):
print(f"Object name: {obj.key}")
if __name__ == "__main__":
main()
Salida esperada:
List all objects after x2.txt:
Object name: z1.txt
Object name: z2.txt
Obtener el tamaño de los objetos en un directorio específico
ObjectIteratorV2 (Recommended)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
def calculate_folder_size(bucket, folder):
"""Calculate the total size of a specified folder."""
total_size = 0
for obj in oss2.ObjectIteratorV2(bucket, prefix=folder):
total_size += obj.size
return total_size
def main():
# Get access credentials from environment variables.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Set the endpoint and region where the bucket is located.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
region = "cn-hangzhou"
# Initialize the bucket.
bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)
# List all objects and folders in the root directory and display their sizes.
print("List the sizes of objects and folders in the root directory:")
for obj in oss2.ObjectIteratorV2(bucket, delimiter='/'):
if obj.is_prefix():
# Calculate the total size of the folder.
folder_size = calculate_folder_size(bucket, obj.key)
print(f"Directory: {obj.key}, Size: {folder_size} bytes")
else:
# Display the object size directly.
print(f"Object: {obj.key}, Size: {obj.size} bytes")
if __name__ == "__main__":
main()
ObjectIterator
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
def calculate_folder_size(bucket, folder):
"""Calculate the total size of a specified folder."""
total_size = 0
for obj in oss2.ObjectIterator(bucket, prefix=folder):
total_size += obj.size
return total_size
def main():
# Get access credentials from environment variables.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Set the endpoint and region where the bucket is located.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
region = "cn-hangzhou"
# Initialize the bucket.
bucket = oss2.Bucket(auth, endpoint, "example-bucket", region=region)
# List all objects and folders in the root directory and display their sizes.
print("List the sizes of objects and folders in the root directory:")
for obj in oss2.ObjectIterator(bucket, delimiter='/'):
if obj.is_prefix():
# Calculate the total size of the folder.
folder_size = calculate_folder_size(bucket, obj.key)
print(f"Directory: {obj.key}, Size: {folder_size} bytes")
else:
# Display the object size directly.
print(f"Object: {obj.key}, Size: {obj.size} bytes")
if __name__ == "__main__":
main()