Todos os produtos
Search
Central de documentação

Object Storage Service:Gerencie o versionamento com o OSS SDK for Python 2.0

Última atualização: Sep 22, 2026

O status de versionamento de um bucket se aplica a todos os objetos nele contidos. Ative o versionamento de um bucket para recuperar uma versão anterior de um objeto caso o sobrescreva ou exclua acidentalmente.

Observações de uso

  • O código de exemplo deste tópico usa o ID de região cn-hangzhou, da região China (Hangzhou). Por padrão, um endpoint público é usado para acessar os recursos de um bucket. Caso precise acessar os recursos do bucket a partir de outro serviço da Alibaba Cloud na mesma região do bucket, utilize um endpoint interno. Para mais informações sobre as regiões e endpoints compatíveis com o OSS, consulte Regions and endpoints.

  • Defina o status de versionamento de um bucket. Para isso, você precisa da permissão oss:PutBucketVersioning. Para obter o status de versionamento de um bucket, é necessária a permissão oss:GetBucketVersioning. Para mais informações, consulte Grant a custom access policy to a RAM user.

Código de exemplo

Configure o status de versionamento de um bucket

Ative o versionamento de um bucket com o seguinte código de exemplo:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser and describe the purpose of the script: enable versioning for a bucket.
parser = argparse.ArgumentParser(description="put bucket versioning sample")

# Define command-line arguments, including the required region and bucket name, and the optional endpoint.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

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

    # Load access credential information from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

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

    # Set the region property of the configuration object based on the command-line arguments provided by the user.
    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

    # Use the preceding configurations to initialize the OSS client to interact with OSS.
    client = oss.Client(cfg)

    # Send a request to enable versioning for the specified bucket.
    result = client.put_bucket_versioning(oss.PutBucketVersioningRequest(
        bucket=args.bucket,  # The name of the bucket.
        versioning_configuration=oss.VersioningConfiguration(
            status='Enabled'  # Enable versioning.
        )
    ))

    # Print the status code and request ID of the operation result to confirm the request status.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          )

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

Consulte o status de versionamento de um bucket

O código de exemplo a seguir demonstra como consultar o status de versionamento de um bucket.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser and describe the purpose of the script: obtain the versioning state of a bucket.
parser = argparse.ArgumentParser(description="get bucket versioning sample")

# Define command-line arguments, including the required region and bucket name, and the optional endpoint.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

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

    # Load access credential information from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

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

    # Set the region property of the configuration object based on the command-line arguments provided by the user.
    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

    # Use the preceding configurations to initialize the OSS client to interact with OSS.
    client = oss.Client(cfg)

    # Send a request to obtain the versioning state of the specified bucket.
    result = client.get_bucket_versioning(oss.GetBucketVersioningRequest(
        bucket=args.bucket,  # The name of the bucket.
    ))

    # Print the status code, request ID, and versioning state of the operation result to confirm the request status.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' version status: {result.version_status},'  # The versioning state.
          )

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

Referências

  • Para acessar o código de exemplo completo que define o status de versionamento de um bucket, consulte put_bucket_version.py.

  • Para acessar o código de exemplo completo que obtém o status de versionamento de um bucket, consulte get_bucket_cors.py.