Tous les produits
Search
Centre de documentation

Object Storage Service:Répertorier les buckets (SDK OSS pour Python V2)

Dernière mise à jour :Aug 18, 2026

Répertoriez les buckets qui répondent aux conditions spécifiées dans toutes les régions de votre compte.

Précautions

  • L'exemple de code utilise par défaut l'ID de région Chine (Hangzhou) cn-hangzhou et un endpoint public. Pour accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région, utilisez un endpoint interne. Pour plus d'informations, consultez Régions et endpoints OSS.

  • L'exemple de code lit les identifiants d'accès à partir des variables d'environnement. Pour plus d'informations, consultez Configurer les identifiants d'accès.

  • Pour répertorier les buckets, vous devez disposer de l'autorisation oss:ListBuckets. Pour plus d'informations, consultez Accorder des autorisations personnalisées à un utilisateur RAM.

  • Spécifiez un ID de groupe de ressources pour filtrer les buckets par groupe de ressources.

    • Par défaut, le paramètre d'ID de groupe de ressources n'est pas inclus dans la requête et la réponse ne contient aucune information sur le groupe de ressources.

    • Si la requête inclut le paramètre d'ID de groupe de ressources, OSS renvoie tous les buckets appartenant à ce groupe de ressources.

    • Si la requête n'inclut pas le paramètre d'ID de groupe de ressources, OSS renvoie tous les buckets dont le demandeur est propriétaire.

Exemple de code

Le code suivant répertorie tous les buckets dans toutes les régions de votre compte.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser and describe the purpose of the script: This sample demonstrates how to list all buckets in OSS.
parser = argparse.ArgumentParser(description="list buckets sample")

# Add the --region command-line argument, which specifies the region where the bucket is located. This is a required parameter.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the --endpoint command-line argument, which specifies the domain names that other services can use to access OSS. This is an optional parameter.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    # Parse the parameters provided on the command line to obtain the user-input values.
    args = parser.parse_args()

    # Load the authentication information required to access OSS from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Create a configuration object using the default configurations of the SDK and set the authentication provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint property in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Initialize the OSS client using the preceding configurations to prepare for interaction with OSS.
    client = oss.Client(cfg)

    # Create a paginator for the ListBuckets operation to handle many buckets.
    paginator = client.list_buckets_paginator()

    # Traverse the paginated results.
    for page in paginator.iter_page(oss.ListBucketsRequest()):
        # For each bucket on each page, print its name, location, and creation date.
        for o in page.buckets:
            print(f'Bucket: {o.name}, Location: {o.location}, Created: {o.creation_date}')

# When this script is directly executed, call the main function to start the processing logic.
if __name__ == "__main__":
    main()  # The entry point of the script, from which the program flow starts.

Scénarios

Répertorier les buckets avec un préfixe spécifié

Le code suivant répertorie les buckets dont les noms commencent par « example » dans toutes les régions de votre compte.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser and describe the purpose of the script: This sample demonstrates how to list all buckets in OSS.
parser = argparse.ArgumentParser(description="list buckets sample")

# Add the --region command-line argument, which specifies the region where the bucket is located. This is a required parameter.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the --endpoint command-line argument, which specifies the domain names that other services can use to access OSS. This is an optional parameter.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    # Parse the parameters provided on the command line to obtain the user-input values.
    args = parser.parse_args()

    # Load the authentication information required to access OSS from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Create a configuration object using the default configurations of the SDK and set the authentication provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint property in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Initialize the OSS client using the preceding configurations to prepare for interaction with OSS.
    client = oss.Client(cfg)

    # Create a paginator for the ListBuckets operation to handle many buckets.
    paginator = client.list_buckets_paginator()

    # Traverse the paginated results.
    for page in paginator.iter_page(oss.ListBucketsRequest(
        prefix='example', # Specify a prefix to list only buckets whose names start with "example".
        ),
    ):
        # For each bucket on each page, print its name, location, and creation date.
        for o in page.buckets:
            print(f'Bucket: {o.name}, Location: {o.location}, Created: {o.creation_date}')

# When this script is directly executed, call the main function to start the processing logic.
if __name__ == "__main__":
    main()  # The entry point of the script, from which the program flow starts.

Répertorier les buckets situés après un marqueur spécifié

Le code suivant répertorie les buckets dont les noms viennent alphabétiquement après « example-bucket » dans toutes les régions de votre compte.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser and describe the purpose of the script: This sample demonstrates how to list all buckets in OSS.
parser = argparse.ArgumentParser(description="list buckets sample")

# Add the --region command-line argument, which specifies the region where the bucket is located. This is a required parameter.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the --endpoint command-line argument, which specifies the domain names that other services can use to access OSS. This is an optional parameter.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    # Parse the parameters provided on the command line to obtain the user-input values.
    args = parser.parse_args()

    # Load the authentication information required to access OSS from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Create a configuration object using the default configurations of the SDK and set the authentication provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint property in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Initialize the OSS client using the preceding configurations to prepare for interaction with OSS.
    client = oss.Client(cfg)

    # Create a paginator for the ListBuckets operation to handle many buckets.
    paginator = client.list_buckets_paginator()

    # Traverse the paginated results.
    for page in paginator.iter_page(oss.ListBucketsRequest(
        marker="example-bucket", # List buckets whose names are alphabetically after "example-bucket".
        ),
    ):
        # For each bucket on each page, print its name, location, and creation date.
        for o in page.buckets:
            print(f'Bucket: {o.name}, Location: {o.location}, Created: {o.creation_date}')

# When this script is directly executed, call the main function to start the processing logic.
if __name__ == "__main__":
    main()  # The entry point of the script, from which the program flow starts.

Répertorier un nombre spécifié de buckets

Le code suivant répertorie les buckets dans toutes les régions de votre compte, avec un nombre maximal spécifié de buckets par page.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser and describe the purpose of the script: This sample demonstrates how to list all buckets in OSS.
parser = argparse.ArgumentParser(description="list buckets sample")

# Add the --region command-line argument, which specifies the region where the bucket is located. This is a required parameter.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the --endpoint command-line argument, which specifies the domain names that other services can use to access OSS. This is an optional parameter.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    # Parse the parameters provided on the command line to obtain the user-input values.
    args = parser.parse_args()

    # Load the authentication information required to access OSS from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Create a configuration object using the default configurations of the SDK and set the authentication provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint property in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Initialize the OSS client using the preceding configurations to prepare for interaction with OSS.
    client = oss.Client(cfg)

    # Create a paginator for the ListBuckets operation to handle many buckets.
    paginator = client.list_buckets_paginator()

    # Traverse the paginated results. Each page contains a specific number of buckets.
    for page in paginator.iter_page(oss.ListBucketsRequest(
        max_keys=10, # Return a maximum of 10 buckets per page.
        ),
    ):
        # For each bucket on each page, print its name, location, and creation date.
        for o in page.buckets:
            print(f'Bucket: {o.name}, Location: {o.location}, Created: {o.creation_date}')

# When this script is directly executed, call the main function to start the processing logic.
if __name__ == "__main__":
    main()  # The entry point of the script, from which the program flow starts.

Répertorier tous les buckets d'un groupe de ressources spécifié

  1. Par défaut, le paramètre d'ID de groupe de ressources n'est pas inclus dans la requête et le résultat XML ne contient aucune information sur le groupe de ressources.

  2. Si vous spécifiez le paramètre resource_group_id dans la requête, OSS renvoie tous les buckets appartenant au groupe de ressources spécifié.

  3. Si vous ne spécifiez pas le paramètre resource_group_id dans la requête, OSS renvoie tous les buckets dont le demandeur est propriétaire.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser and describe the purpose of the script: This sample demonstrates how to list all buckets in OSS.
parser = argparse.ArgumentParser(description="list buckets sample")

# Add the --region command-line argument, which specifies the region where the bucket is located. This is a required parameter.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the --endpoint command-line argument, which specifies the domain names that other services can use to access OSS. This is an optional parameter.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    # Parse the parameters provided on the command line to obtain the user-input values.
    args = parser.parse_args()

    # Load the authentication information required to access OSS from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Create a configuration object using the default configurations of the SDK and set the authentication provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint property in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Initialize the OSS client using the preceding configurations to prepare for interaction with OSS.
    client = oss.Client(cfg)

    # Create a paginator for the ListBuckets operation to handle many buckets.
    paginator = client.list_buckets_paginator()

    # Traverse the paginated results. Each page contains a specific number of buckets.
    for page in paginator.iter_page(oss.ListBucketsRequest(
        max_keys=10, # Return a maximum of 10 buckets per page.
        resource_group_id="rg-aek27tc********", # List buckets in the specified resource group.
        ),
    ):
        # For each bucket on each page, print its name, location, creation date, and resource group ID.
        for o in page.buckets:
            print(f'Bucket: {o.name}, Location: {o.location}, Created: {o.creation_date}, Resource Group ID: {o.resource_group_id}')

# When this script is directly executed, call the main function to start the processing logic.
if __name__ == "__main__":
    main()  # The entry point of the script, from which the program flow starts.

Références