OSS SDK pour Python fournit des itérateurs encapsulés permettant de répertorier les objets d'un bucket. Utilisez ces itérateurs pour filtrer les objets par préfixe, position de départ et autres critères.
Utilisation
OSS SDK pour Python propose deux itérateurs pour répertorier les objets : ObjectIterator, qui repose sur l'opération GetBucket (ListObjects), et ObjectIteratorV2, qui repose sur l'opération ListObjectsV2 (GetBucketV2). Les principales différences sont les suivantes :
ObjectIterator: renvoie les informations du propriétaire par défaut.-
ObjectIteratorV2: utilise le paramètrefetch_ownerpour indiquer s'il faut renvoyer les informations du propriétaire.L'utilisation de
ObjectIteratorV2nécessite OSS SDK pour Python version 2.12.0 ou ultérieure.
Nous recommandons ObjectIteratorV2 pour sa prise en charge améliorée des buckets avec versioning activé.
-
Constructeur ObjectIteratorV2
oss2.ObjectIteratorV2(bucket, prefix='', delimiter='', continuation_token='', start_after='', fetch_owner=False, encoding_type = 'url', max_keys=100, max_retries=None, headers=None) -
Constructeur ObjectIterator
oss2.ObjectIterator(bucket, prefix='', delimiter='', marker='', max_keys=100, max_retries=None, headers=None)
Exemples de code
Avant d'exécuter le code, installez OSS SDK pour Python et configurez les variables d'environnement pour les identifiants d'accès. Pour plus d'informations, consultez la rubrique Démarrage rapide avec OSS SDK pour Python. Un compte Alibaba Cloud dispose de toutes les autorisations par défaut. Si vous utilisez un utilisateur RAM ou un rôle RAM, assurez-vous que l'utilisateur ou le rôle dispose de l'autorisation oss:ListObjects.
Répertorier tous les objets
ObjectIteratorV2 (recommandé)
#!/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()
Pour récupérer les informations du propriétaire des objets, définissez 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()
Répertorier un nombre spécifique d'objets
ObjectIteratorV2 (recommandé)
#!/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()
Répertorier les objets avec un préfixe spécifique
Supposons qu'un bucket contienne quatre objets : oss.jpg, fun/test.jpg, fun/movie/001.avi et fun/movie/007.avi. La barre oblique (/) est utilisée comme séparateur de dossier.
ObjectIteratorV2 (recommandé)
#!/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()
Sortie attendue :
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()
Sortie attendue :
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
Répertorier les objets et sous-répertoires dans un répertoire spécifique
OSS ne possède pas le concept de dossiers. Tous les éléments sont stockés sous forme d'objets. Pour créer un dossier, vous pouvez créer un objet de zéro octet se terminant par une barre oblique (/). La console OSS affiche les objets se terminant par une barre oblique (/) sous forme de dossiers.
Vous pouvez utiliser les paramètres delimiter et prefix pour simuler la fonctionnalité des dossiers.
Si vous définissez
prefixsur un nom de dossier, l'opération répertorie tous les objets dont les clés commencent par ce préfixe. Cela permet de répertorier de manière récursive tout le contenu du dossier simulé.Si vous définissez également
delimitersur une barre oblique (/), l'opération répertorie uniquement les objets et les noms de sous-répertoires au niveau supérieur de ce dossier. Les objets situés dans les sous-répertoires ne sont pas répertoriés.
ObjectIteratorV2 (recommandé)
#!/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()
Sortie attendue :
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()
Sortie attendue :
List objects and subdirectories in the fun directory:
Subdirectory: fun/movie/
Object: fun/test.jpg
Répertorier les objets après une position de départ spécifique
Supposons qu'un bucket contienne les quatre objets suivants : x1.txt, x2.txt, z1.txt et z2.txt.
ObjectIteratorV2 (recommandé)
#!/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()
Sortie attendue :
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()
Sortie attendue :
List all objects after x2.txt:
Object name: z1.txt
Object name: z2.txt
Obtenir la taille des objets dans un répertoire spécifique
ObjectIteratorV2 (recommandé)
#!/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()