Todos os produtos
Search
Central de documentação

Object Storage Service:Converter as classes de armazenamento de objetos usando o OSS SDK for Python 1.0

Última atualização: Jul 03, 2026

O Object Storage Service (OSS) oferece as seguintes classes de armazenamento para atender a diversos cenários, desde dados quentes até dados frios: Standard, Infrequent Access (IA), Archive, Cold Archive e Deep Cold Archive. No OSS, após a criação de um objeto, não é possível modificar seu conteúdo. Para converter a classe de armazenamento de um objeto, use o método Bucket.CopyObject para copiá-lo e criar um novo objeto com a classe de armazenamento desejada.

Observações

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

  • Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para saber como configurar credenciais de acesso, consulte Configurar credenciais de acesso (Python SDK V1).

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

  • Para converter a classe de armazenamento de um objeto, você precisa das permissões oss:GetObject, oss:PutObject e oss:RestoreObject. Para mais informações, consulte Conceder uma política personalizada.

Exemplos

Importante

Se você converter a classe de armazenamento de um objeto IA, Archive, Cold Archive ou Deep Cold Archive, ou excluí-lo antes do término da duração mínima de armazenamento, haverá cobrança pelo uso de armazenamento referente ao período inferior ao mínimo exigido. Para mais informações, consulte Como sou cobrado por objetos cuja duração de armazenamento é menor que a duração mínima?

Converter a classe de armazenamento de um objeto de Standard ou IA para Archive, Cold Archive ou Deep Cold Archive

O código de exemplo a seguir converte a classe de armazenamento de um objeto de Standard ou IA para Archive, Cold Archive ou Deep Cold Archive:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
import os
# 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 bucket region (for example: 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)

# Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. 
# Make sure that the storage class of the object is Standard or IA. 
object_name = 'exampledir/exampleobject.txt'

# Convert the storage class of the object to Archive by setting the x-oss-storage-class header to oss2.BUCKET_STORAGE_CLASS_ARCHIVE. 
headers = {'x-oss-storage-class': oss2.BUCKET_STORAGE_CLASS_ARCHIVE}
# Convert the storage class of the object to Cold Archive by setting the x-oss-storage-class header to oss2.BUCKET_STORAGE_CLASS_COLD_ARCHIVE. 
# headers = {'x-oss-storage-class': oss2.BUCKET_STORAGE_CLASS_COLD_ARCHIVE}
# Convert the storage class of the object to Deep Cold Archive by setting the x-oss-storage-class header to BUCKET_STORAGE_CLASS_DEEP_COLD_ARCHIVE 
# headers = {'x-oss-storage-class': oss2.models.BUCKET_STORAGE_CLASS_DEEP_COLD_ARCHIVE}
# Convert the storage class of the object. 
bucket.copy_object(bucket.bucket_name, object_name, object_name, headers)                    

Converter a classe de armazenamento de um objeto de Archive para Standard ou IA

O código de exemplo a seguir converte a classe de armazenamento de um objeto de Archive para Standard ou IA:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
import os
import time
# 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 bucket region (for example: 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)

# Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. 
# Make sure that the storage class of the object is Archive. 
object_name = 'exampledir/exampleobject.txt'

# Obtain the object metadata. 
meta = bucket.head_object(object_name)

# Restore the object. The amount of time required to restore an object varies based on the size of the object. 
if meta.resp.headers['x-oss-storage-class'] == oss2.BUCKET_STORAGE_CLASS_ARCHIVE:
    bucket.restore_object(object_name)
    while True:
        meta = bucket.head_object(object_name)
        if meta.resp.headers['x-oss-restore'] == 'ongoing-request="true"':
            time.sleep(5)
        else:
            break

# Convert the storage class of the object to Standard by setting the x-oss-storage-class header to oss2.BUCKET_STORAGE_CLASS_STANDARD. 
headers = {'x-oss-storage-class': oss2.BUCKET_STORAGE_CLASS_STANDARD}
# Convert the storage class of the object to IA by setting the x-oss-storage-class header to oss2.BUCKET_STORAGE_CLASS_IA. 
# headers = {'x-oss-storage-class': oss2.BUCKET_STORAGE_CLASS_IA}

# Convert the storage class of the object. 
bucket.copy_object(bucket.bucket_name, object_name, object_name, headers)

Converter a classe de armazenamento de um objeto de Cold Archive para Standard ou IA

O código de exemplo a seguir converte a classe de armazenamento de um objeto de Cold Archive para Standard ou IA:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
import os
import time
from oss2.models import RESTORE_TIER_EXPEDITED, RestoreJobParameters

# 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 bucket region (for example: 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)

# Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. 
# Make sure that the storage class of the object is Cold Archive. 
object_name = 'exampledir/exampleobject.txt'

# Obtain the object metadata. 
meta = bucket.head_object(object_name)

# Restore the object. 
if meta.resp.headers['x-oss-storage-class'] == oss2.BUCKET_STORAGE_CLASS_COLD_ARCHIVE:
    # Specify the restoration priority. RESTORE_TIER_EXPEDITED specifies that the object is restored within 1 hour. 
    job_parameters = RestoreJobParameters(RESTORE_TIER_EXPEDITED)
    # Specify the duration for which the object can remain in the restored state. Unit: days.     
    restore_config = oss2.models.RestoreConfiguration(days=5, job_parameters=job_parameters)
    bucket.restore_object(object_name, input=restore_config)
    while True:
        meta = bucket.head_object(object_name)
        if meta.resp.headers['x-oss-restore'] == 'ongoing-request="true"':
            time.sleep(5)
        else:
            break
# Convert the storage class of the object to Standard by setting the x-oss-storage-class header to oss2.BUCKET_STORAGE_CLASS_STANDARD. 
headers = {'x-oss-storage-class': oss2.BUCKET_STORAGE_CLASS_STANDARD}
# Convert the storage class of the object to IA by setting the x-oss-storage-class header to oss2.BUCKET_STORAGE_CLASS_IA. 
# headers = {'x-oss-storage-class': oss2.BUCKET_STORAGE_CLASS_IA}

# Convert the storage class of the object. 
bucket.copy_object(bucket.bucket_name, object_name, object_name, headers)

Referências

Para obter mais informações sobre a operação de API usada para converter a classe de armazenamento de um objeto, consulte CopyObject.