Todos os produtos
Search
Central de documentação

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

Última atualização: Jul 03, 2026

Com o Alibaba Cloud OSS SDK for Python, você configura regras de acesso com base no cabeçalho de requisição Referer. Defina uma lista de permissões de Referer, uma lista de bloqueios de Referer e especifique se cabeçalhos Referer vazios são permitidos. Essas configurações impedem que cabeçalhos Referer específicos acessem seus arquivos do OSS, evitam o uso não autorizado dos recursos e reduzem custos desnecessários de tráfego.

Pré-requisitos

  • Antes de configurar a proteção contra hotlink, compreenda esse recurso. Para mais informações, consulte Proteção contra hotlink.

  • Os exemplos de código neste tópico usam a região China (Hangzhou) (ID: cn-hangzhou) como referência. Por padrão, o sistema usa 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 mais detalhes sobre as regiões do OSS e os respectivos endpoints, consulte Regiões e endpoints do OSS.

  • Para definir ou excluir configurações de proteção contra hotlink, você precisa da permissão oss:PutBucketReferer. Para obter as configurações de proteção contra hotlink, você precisa da permissão oss:GetBucketReferer. Para mais informações, consulte Conceder permissões personalizadas a um usuário RAM.

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

Parâmetros da requisição. Para mais informações, consulte PutBucketRefererRequest

GetBucketRefererRequest

Parâmetros da requisição. Para mais informações, consulte GetBucketRefererRequest

Valores de retorno

Tipo

Descrição

PutBucketRefererResult

Valor de retorno. Para mais informações, consulte PutBucketRefererResult

GetBucketRefererResult

Valor de retorno. Para mais informações, consulte GetBucketRefererResult

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

Para a definição completa do método de obtenção das 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 solucionar erros comuns durante a configuração da proteção contra hotlink, consulte 33-REFERER.

  • O código de exemplo completo para definir a proteção contra hotlink está disponível em put_bucket_referer.py.

  • O código de exemplo completo para obter as configurações de proteção contra hotlink encontra-se em get_bucket_referer.py.