Todos los productos
Search
Centro de documentos

Object Storage Service:Protección contra hotlinking (SDK de Python V2)

Última actualización: Sep 03, 2026

El SDK de Alibaba Cloud OSS para Python permite configurar reglas de acceso basadas en el encabezado de solicitud Referer. Entre las opciones disponibles se encuentran establecer una lista de permitidos de Referer, una lista de bloqueados de Referer y especificar si se permiten encabezados Referer vacíos. Esta configuración impide que encabezados Referer específicos accedan a sus archivos de OSS, evita el uso no autorizado de sus recursos y reduce costos de tráfico innecesarios.

Requisitos previos

  • Antes de configurar la protección contra hotlinking, asegúrese de comprender esta función. Para obtener más información, consulte Hotlink protection.

  • El código de ejemplo de este tema usa la región China (Hangzhou) (ID: cn-hangzhou) como referencia. De forma predeterminada, se usa el endpoint público. Si desea acceder a OSS desde otros servicios de Alibaba Cloud en la misma región, utilice el endpoint interno. Para obtener más información sobre las regiones de OSS y sus endpoints correspondientes, consulte OSS regions and endpoints.

  • Para establecer o eliminar configuraciones de protección contra hotlinking, debe contar con el permiso oss:PutBucketReferer. Para recuperar dichas configuraciones, requiere el permiso oss:GetBucketReferer. Para obtener más información, consulte Grant custom permissions to a RAM user.

Definiciones de métodos

Establecer la protección contra hotlinking

put_bucket_referer(request: PutBucketRefererRequest, **kwargs) → PutBucketRefererResult

Obtener la configuración de protección contra hotlinking

get_bucket_referer(request: GetBucketRefererRequest, **kwargs) → GetBucketRefererResult

Parámetros de solicitud

Parámetro

Tipo

Descripción

request

PutBucketRefererRequest

Los parámetros de la solicitud. Para obtener más información, consulte PutBucketRefererRequest

GetBucketRefererRequest

Los parámetros de la solicitud. Para obtener más información, consulte GetBucketRefererRequest

Valores de retorno

Tipo

Descripción

PutBucketRefererResult

El valor de retorno. Para obtener más información, consulte PutBucketRefererResult

GetBucketRefererResult

El valor de retorno. Para obtener más información, consulte GetBucketRefererResult

Para consultar la definición completa del método que establece la protección contra hotlinking, revise put_bucket_referer.

Para consultar la definición completa del método que recupera la configuración de protección contra hotlinking, revise get_bucket_referer.

Ejemplos

Establecer la protección contra hotlinking

Utilice el siguiente código para establecer la protección contra hotlinking.

import argparse
import alibabacloud_oss_v2 as oss

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

# Define command-line arguments, including the required region, bucket name, and 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 command-line arguments to obtain user-entered 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 for interacting with OSS.
    client = oss.Client(cfg)

    # Send a request to set the hotlink protection configuration for the specified bucket.
    result = client.put_bucket_referer(oss.PutBucketRefererRequest(
            bucket=args.bucket,  # The bucket name.
            referer_configuration=oss.RefererConfiguration(
                allow_empty_referer=True,  # Specifies whether to allow empty Referer headers. Default value: True.
                allow_truncate_query_string=False,  # Specifies whether to truncate the query string. Default value: False.
                truncate_path=False,  # Specifies whether to truncate the path. Default value: False.
                referer_list=oss.RefererList(
                    referers=['http://www.aliyun.com', 'https://www.aliyun.com'],  # The list of allowed Referer headers.
                ),
                referer_blacklist=oss.RefererBlacklist(
                    referers=['http://www.refuse.com', 'http://www.refuse1.com'],  # The blacklist of denied Referer headers.
                ),
            ),
    ))

    # 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, from which the program flow starts.

Obtener la configuración de protección contra hotlinking

Utilice el siguiente código para recuperar la configuración de protección contra hotlinking.

import argparse
import alibabacloud_oss_v2 as oss

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

# Define command-line arguments, including the required region, bucket name, and 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 command-line arguments to obtain user-entered 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 for interacting with OSS.
    client = oss.Client(cfg)

    # Send a request to obtain the hotlink protection configuration for the specified bucket.
    result = client.get_bucket_referer(oss.GetBucketRefererRequest(
            bucket=args.bucket,  # The bucket name.
    ))

    # Print the status code, request ID, and hotlink protection configuration details of the operation result to confirm the request status and configuration details.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' allow empty referer: {getattr(result.referer_configuration, "allow_empty_referer", "Not set")},'
          f' allow truncate query string: {getattr(result.referer_configuration, "allow_truncate_query_string", "Not set")},'
          f' truncate path: {getattr(result.referer_configuration, "truncate_path", "Not set")},'
          f' referer list: {getattr(result.referer_configuration, "referer_list", "Not set")},'
          f' referer blacklist: {getattr(result.referer_configuration, "referer_blacklist", "Not set")},'
          )

# 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, from which the program flow starts.

Referencias

  • Para obtener información sobre cómo solucionar errores comunes al configurar la protección contra hotlinking, consulte 33-REFERER.

  • Para consultar el código de ejemplo completo para establecer la protección contra hotlinking, revise put_bucket_referer.py.

  • Para consultar el código de ejemplo completo para recuperar la configuración de protección contra hotlinking, revise get_bucket_referer.py.