Todos os produtos
Search
Central de documentação

Object Storage Service:Proteção contra hotlink (Python SDK V2)

Última atualização: Sep 24, 2026

Use o Alibaba Cloud OSS SDK for Python para configurar regras de acesso com base no cabeçalho de requisição Referer, como definir uma lista de permissões de Referer, uma lista de bloqueios de Referer e especificar se cabeçalhos Referer vazios são permitidos. Essas configurações impedem que cabeçalhos Referer específicos acessem seus arquivos do OSS, evitando o uso não autorizado dos seus recursos e custos desnecessários de tráfego.

Pré-requisitos

  • Antes de configurar a proteção contra hotlink, certifique-se de entender este recurso. Para mais informações, consulte Hotlink protection.

  • O código de exemplo neste tópico usa a região China (Hangzhou) (ID: cn-hangzhou) como exemplo. Por padrão, o SDK utiliza o endpoint público. Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use o endpoint interno. Para obter mais informações sobre as regiões do OSS e seus respectivos endpoints, consulte OSS regions and endpoints.

  • Para definir ou excluir configurações de proteção contra hotlink, você deve ter a permissão oss:PutBucketReferer. Para obter as configurações de proteção contra hotlink, você deve ter a permissão oss:GetBucketReferer. Para saber mais, consulte Grant custom permissions to a RAM user.

Definições de métodos

Definir proteção contra hotlink

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

Obter configurações de proteção contra hotlink

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

Parâmetros da requisição

Parâmetro

Tipo

Descrição

request

PutBucketRefererRequest

Os parâmetros da requisição. Para mais detalhes, consulte PutBucketRefererRequest

GetBucketRefererRequest

Os parâmetros da requisição. Para mais detalhes, consulte GetBucketRefererRequest

Valores de retorno

Tipo

Descrição

PutBucketRefererResult

O valor de retorno. Para mais detalhes, consulte PutBucketRefererResult

GetBucketRefererResult

O valor de retorno. Para mais detalhes, consulte GetBucketRefererResult

Para a definição completa do método para configurar a proteção contra hotlink, consulte put_bucket_referer.

Para a definição completa do método para obter as configurações de proteção contra hotlink, consulte get_bucket_referer.

Exemplos

Definir proteção contra hotlink

Use o código a seguir para definir a proteção contra hotlink.

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.

Obter configurações de proteção contra hotlink

Use o código a seguir para obter as configurações de proteção contra hotlink.

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.

Referências

  • Para obter informações sobre como solucionar erros comuns que ocorrem ao configurar a proteção contra hotlink, consulte 33-REFERER.

  • Para o código de exemplo completo para configurar a proteção contra hotlink, consulte put_bucket_referer.py.

  • Para o código de exemplo completo para obter as configurações de proteção contra hotlink, consulte get_bucket_referer.py.