Todos os produtos
Search
Central de documentação

Object Storage Service:Manage versioning (OSS SDK for Python 1.0)

Última atualização: Jul 03, 2026

O estado de versionamento de um bucket aplica-se a todos os objetos nele contidos. Ao ativar o versionamento, você recupera qualquer versão anterior de um objeto caso ele seja sobrescrito ou excluído acidentalmente.

Um bucket pode apresentar os seguintes estados de versionamento: desativado (padrão), ativado ou suspenso. Para obter mais informações sobre versionamento, consulte Versionamento.

Observações

  • Este tópico utiliza o endpoint público da região China (Hangzhou). Caso acesse o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para mais detalhes sobre regiões e endpoints do OSS, consulte Regiões e endpoints.

  • As credenciais de acesso neste exemplo são obtidas por meio de variáveis de ambiente. Para saber como configurar essas credenciais, consulte Configurar credenciais de acesso (Python SDK V1).

  • O exemplo abaixo demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para outras configurações, como uso de domínio personalizado ou autenticação via Security Token Service (STS), consulte Inicialização.

  • Para definir o estado de versionamento de um bucket, é necessária a permissão oss:PutBucketVersioning. Já para consultar informações sobre esse estado, você precisa da permissão oss:GetBucketVersioning. Para mais informações, consulte Conceder uma política de acesso personalizada a um usuário RAM.

Configurar o versionamento de um bucket

O código a seguir exemplifica como ativar ou suspender o versionamento de um bucket:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import BucketVersioningConfig
# 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)

# Initialize versioning configurations for the bucket. 
config = BucketVersioningConfig()
# Set the versioning state to enabled or suspended. 
config.status = oss2.BUCKET_VERSIONING_ENABLE

# Configure versioning for the bucket. 
result = bucket.put_bucket_versioning(config)
# View the HTTP status code. 
print('http response code:', result.status)

Consultar o estado de versionamento de um bucket

Use o código abaixo como exemplo para consultar o estado de versionamento de um 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)

# Query the versioning state of the bucket. 
versioning_info = bucket.get_bucket_versioning()
# Display the versioning state of the bucket. If versioning has been enabled, Enabled or Suspended is returned. If versioning has not been enabled, None is returned. 
print('bucket versioning status:', versioning_info.status)

Referências

  • Acesse o repositório no GitHub para visualizar o código de exemplo completo de configuração de versionamento de bucket.

  • Consulte a documentação da operação de API PutBucketVersioning para configurar o versionamento de um bucket.

  • Veja a operação de API GetBucketVersioning para obter detalhes sobre como consultar o estado de versionamento.