Todos los productos
Search
Centro de documentos

Object Storage Service:Replicación de datos (Python SDK V1)

Última actualización: Sep 03, 2026

La replicación de datos copia de forma asíncrona los objetos y sus operaciones de creación, actualización y eliminación desde un bucket de origen hacia un bucket de destino en tiempo casi real. OSS admite cross-region replication (CRR) y replicación en la misma región (SRR).

Notas

  • En este tema se utiliza el endpoint público de la región China (Hangzhou). Si desea acceder a OSS desde otros servicios de Alibaba Cloud en la misma región que OSS, utilice un endpoint interno. Para obtener más información sobre las regiones y endpoints de OSS, consulte Regions and endpoints.

  • En este tema, las credenciales de acceso se obtienen de variables de entorno. Para obtener más información sobre cómo configurar las credenciales de acceso, consulte Configure access credentials using OSS SDK for Python 1.0.

  • Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Initialization.

  • Para habilitar la replicación de datos, requiere el permiso oss:PutBucketReplication. Para consultar las reglas de replicación de datos, requiere el permiso oss:GetBucketReplication. Para consultar las regiones a las que se pueden replicar los datos, requiere el permiso oss:GetBucketReplicationLocation. Para consultar el progreso de una tarea de replicación de datos, requiere el permiso oss:GetBucketReplicationProgress. Para deshabilitar la replicación de datos, requiere el permiso oss:DeleteBucketReplication. Para obtener más información, consulte Grant a custom policy.

Habilitar la replicación de datos

Importante

Antes de habilitar la replicación de datos, asegúrese de que los buckets de origen y de destino no tengan versionado o lo tengan habilitado.

El siguiente código habilita la replicación de datos desde srcexamplebucket en la región China (Hangzhou) hacia destexamplebucket en la misma región o en una diferente.

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import ReplicationRule
# Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the region information that corresponds to the endpoint, for example, cn-hangzhou. Note that this parameter is required for V4 signatures.
region = "cn-hangzhou"

# Specify the bucket name, for example, examplebucket.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)

replica_config = ReplicationRule(
    # Specify the destination bucket to which you want to replicate data.
    target_bucket_name='destexamplebucket',
    # Specify the region where the destination bucket is located.
    # If you want to enable cross-region replication, the source and destination buckets must be in different regions. If you want to enable same-region replication, the source and destination buckets must be in the same region.
    target_bucket_location='yourTargetBucketLocation'
)

# Specify the prefixes of the objects to replicate. After you specify prefixes, only objects that match the prefixes are replicated to the destination bucket.
# prefix_list = ['prefix1', 'prefix2']
# Set the data replication rule.
# replica_config = ReplicationRule(
     # prefix_list=prefix_list,
     # Replicate object creation and update operations in the source bucket to the destination bucket.
     # action_list=[ReplicationRule.PUT],
     # Specify the destination bucket to which you want to replicate data.
     # target_bucket_name='destexamplebucket1',
     # Specify the region where the destination bucket is located.
     # target_bucket_location='yourTargetBucketLocation',
     # By default, historical data is replicated. In this example, this parameter is set to False to disable historical data replication.
     # is_enable_historical_object_replication=False,
     # Specify the data transmission link for data replication.
     # target_transfer_type='oss_acc',
     # Specify the role that OSS is authorized to use for data replication. This element is required if you use SSE-KMS to encrypt destination objects.
     # sync_role_name='roleNameTest',
     # Replicate objects that are created with SSE-KMS encryption.
     # sse_kms_encrypted_objects_status=ReplicationRule.ENABLED
     # Specify the SSE-KMS key ID. This element is required if you replicate objects that are created with SSE-KMS encryption.
     # replica_kms_keyid='9468da86-3509-4f8d-a61e-6eab1eac****',
  #)

# Enable data replication.
bucket.put_bucket_replication(replica_config)

Consultar reglas de replicación de datos

El siguiente código consulta las reglas de replicación de datos para examplebucket.

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import ReplicationRule

# Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the region information that corresponds to the endpoint, for example, cn-hangzhou. Note that this parameter is required for V4 signatures.
region = "cn-hangzhou"

# Specify the bucket name, for example, examplebucket.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)

# View the data replication rules.
result = bucket.get_bucket_replication()
# Print the returned information.
for rule in result.rule_list:
    print(rule.rule_id)
    print(rule.target_bucket_name)
    print(rule.target_bucket_location)

Consultar regiones de destino disponibles para replicación

El siguiente código enumera las regiones de destino a las que se pueden replicar los datos de examplebucket.

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import ReplicationRule

# Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the region information that corresponds to the endpoint, for example, cn-hangzhou. Note that this parameter is required for V4 signatures.
region = "cn-hangzhou"

# Specify the bucket name, for example, examplebucket.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)

# View the destination regions available for replication.
result = bucket.get_bucket_replication_location()
for location in result.location_list:
    print(location)

Consultar el progreso de la replicación de datos

Puede consultar el progreso de las tareas de replicación de datos históricos y de las tareas de replicación de datos incrementales.

  • El progreso de las tareas de replicación de datos históricos se expresa como porcentaje. Solo puede consultar el progreso de estas tareas en los buckets que tienen habilitada la replicación de datos históricos.

  • El progreso de las tareas de replicación de datos incrementales se expresa como un punto en el tiempo. Los datos almacenados en el bucket de origen antes de dicho punto ya se han replicado.

El siguiente código consulta el progreso de la replicación de datos para la regla con ID test_replication_1 en examplebucket.

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import ReplicationRule

# Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the region information that corresponds to the endpoint, for example, cn-hangzhou. Note that this parameter is required for V4 signatures.
region = "cn-hangzhou"

# Specify the bucket name, for example, examplebucket.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)

# View the data replication progress.
# Specify the replication rule ID, for example, test_replication_1.
result = bucket.get_bucket_replication_progress('test_replication_1')
print(result.progress.rule_id)
# Check whether historical data replication is enabled.
print(result.progress.is_enable_historical_object_replication)
# Historical data replication progress.
print(result.progress.historical_object_progress)
# Real-time data replication progress.
print(result.progress.new_object_progress)            

Deshabilitar la replicación de datos

Para deshabilitar la replicación de datos entre un bucket de origen y uno de destino, elimine la regla de replicación del bucket.

El siguiente código elimina la regla de replicación con ID test_replication_1 de examplebucket.

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import ReplicationRule

# Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the region information that corresponds to the endpoint, for example, cn-hangzhou. Note that this parameter is required for V4 signatures.
region = "cn-hangzhou"

# Specify the bucket name, for example, examplebucket.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)

# Disable data replication. After this operation, replicated objects remain in the destination bucket, but new changes from the source bucket stop replicating.
# Specify the replication rule ID, for example, test_replication_1.
result = bucket.delete_bucket_replication('test_replication_1')

Referencias

  • Para ver el código de ejemplo completo sobre replicación de datos, consulte GitHub.

  • Para obtener más información sobre la operación de API para habilitar la replicación de datos, consulte PutBucketReplication.

  • Para obtener más información sobre la operación de API para consultar reglas de replicación de datos, consulte GetBucketReplication.

  • Para obtener más información sobre la operación de API para consultar regiones de destino disponibles para replicación, consulte GetBucketReplicationLocation.

  • Para obtener más información sobre la operación de API para consultar el progreso de la replicación de datos, consulte GetBucketReplicationProgress.

  • Para obtener más información sobre la operación de API para deshabilitar la replicación de datos, consulte DeleteBucketReplication.