Tous les produits
Search
Centre de documentation

Object Storage Service:Protection contre le hotlinking (SDK Python V2)

Dernière mise à jour :Sep 24, 2026

Le SDK Alibaba Cloud OSS pour Python vous permet de configurer des règles d'accès basées sur l'en-tête de requête Referer. Vous pouvez ainsi définir une liste blanche Referer, une liste noire Referer et indiquer si les en-têtes Referer vides sont autorisés. Ces configurations bloquent l'accès à vos fichiers OSS depuis des en-têtes Referer spécifiques, empêchent l'utilisation non autorisée de vos ressources et évitent des coûts de trafic inutiles.

Prérequis

  • Avant de configurer la protection contre le hotlinking, assurez-vous de bien comprendre cette fonctionnalité. Pour plus d'informations, consultez la rubrique Protection contre le hotlinking.

  • Le code exemple de cette rubrique utilise la région Chine (Hangzhou) (ID : cn-hangzhou) à titre d'exemple. L'endpoint public est utilisé par défaut. Si vous souhaitez accéder à OSS depuis d'autres services Alibaba Cloud dans la même région, utilisez l'endpoint interne. Pour plus d'informations sur les régions OSS et leurs endpoints correspondants, consultez la rubrique Régions et endpoints OSS.

  • Pour définir ou supprimer les configurations de protection contre le hotlinking, vous devez disposer de l'autorisation oss:PutBucketReferer. Pour récupérer les configurations de protection contre le hotlinking, vous devez disposer de l'autorisation oss:GetBucketReferer. Pour plus d'informations, consultez la rubrique Accorder des autorisations personnalisées à un utilisateur RAM.

Définitions des méthodes

Définir la protection contre le hotlinking

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

Obtenir les paramètres de protection contre le hotlinking

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

Paramètres de requête

Paramètre

Type

Description

request

PutBucketRefererRequest

Les paramètres de la requête. Pour plus d'informations, consultez PutBucketRefererRequest

GetBucketRefererRequest

Les paramètres de la requête. Pour plus d'informations, consultez GetBucketRefererRequest

Valeurs de retour

Type

Description

PutBucketRefererResult

La valeur de retour. Pour plus d'informations, consultez PutBucketRefererResult

GetBucketRefererResult

La valeur de retour. Pour plus d'informations, consultez GetBucketRefererResult

Pour la définition complète de la méthode permettant de définir la protection contre le hotlinking, consultez la rubrique put_bucket_referer.

Pour la définition complète de la méthode permettant de récupérer les paramètres de protection contre le hotlinking, consultez la rubrique get_bucket_referer.

Exemples

Définir la protection contre le hotlinking

Utilisez le code suivant pour définir la protection contre le 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.

Obtenir les paramètres de protection contre le hotlinking

Utilisez le code suivant pour récupérer les configurations de protection contre le 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.

Références

  • Pour savoir comment résoudre les erreurs courantes lors de la configuration de la protection contre le hotlinking, consultez la rubrique 33-REFERER.

  • Pour obtenir le code exemple complet permettant de définir la protection contre le hotlinking, consultez la rubrique put_bucket_referer.py.

  • Pour obtenir le code exemple complet permettant de récupérer les configurations de protection contre le hotlinking, consultez la rubrique get_bucket_referer.py.