Tüm Ürünler
Search
Belge Merkezi

Object Storage Service:OSS Python SDK 2.0 ile özel alan adlarını eşleme

Son Güncelleme:Oct 02, 2026

Nesneleri bir pakete yükledikten sonra Object Storage Service (OSS), yüklenen nesneler için paketin genel uç noktasını içeren URL'leri otomatik olarak oluşturur. Nesnelere erişmek için bu URL'leri kullanabilirsiniz. Nesnelere özel bir alan adı kullanarak erişmek istiyorsanız, özel alan adının nesnelerin depolandığı paketle eşlenmesi için bir CNAME kaydı eklemeniz gerekir.

Kullanım notları

  • Bu konudaki örnek kod, China (Hangzhou) bölgesinin bölge kimliği olan cn-hangzhou değerini kullanır. Bir paketteki kaynaklara varsayılan olarak genel uç nokta üzerinden erişilir. Paketin bulunduğu bölgedeki diğer Alibaba Cloud hizmetlerini kullanarak paketteki kaynaklara erişmek istiyorsanız dahili uç nokta kullanın. OSS bölgeleri ve uç noktaları hakkında daha fazla bilgi için bkz. Bölgeler ve uç noktalar.

Örnekler

CNAME belirteci oluşturma

Aşağıdaki örnek kod, CNAME belirtecinin nasıl oluşturulacağını gösterir:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command line parameter parser and describe the purpose of the script. The example describes how to create a CNAME token.
parser = argparse.ArgumentParser(description="create cname token sample")

# Specify the command line parameters, including the region, bucket name, endpoint, and custom domain name.
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')
parser.add_argument('--domain', help='The custom domain name.', required=True)

def main():
    # Parse the command line parameters to obtain the values entered by the user.
    args = parser.parse_args()

    # Obtain the access credentials from environment variables for identity authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configurations of the SDK to create a configuration object and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Specify the region attribute of the configuration object based on the command line parameters provided by the user.
    cfg.region = args.region

    # If a custom endpoint is provided, modify the endpoint parameter in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSSClient instance and allow the instance to interact with OSS.
    client = oss.Client(cfg)

    # Send a request to create a CNAME token for the bucket.
    result = client.create_cname_token(oss.CreateCnameTokenRequest(
            bucket=args.bucket, # The name of the bucket.
            bucket_cname_configuration=oss.BucketCnameConfiguration(
                cname=oss.Cname(
                    domain=args.domain, # The custom domain name.
                ),
            ),
    ))

    # Display the status code of the operation result and other relevant information to check the request status and CNAME token details.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' cname: {result.cname_token.cname if hasattr(result.cname_token, "cname") else "Not set"},'
          f' token: {result.cname_token.token if hasattr(result.cname_token, "token") else "Not set"},'
          f' expire time: {result.cname_token.expire_time.strftime("%Y-%m-%dT%H:%M:%S.000Z") if hasattr(result.cname_token, "expire_time") else "Not set"},'
          f' bucket: {result.cname_token.bucket if hasattr(result.cname_token, "bucket") else "Not set"},'
          )

# Call the main function to start the processing logic when the script is directly run.
if __name__ == "__main__":
    main() # Specify the entry points in the functions of the script. The control program flow starts here.

CNAME belirtecini sorgulama

Aşağıdaki örnek kod, CNAME belirtecinin nasıl sorgulanacağını gösterir:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command line parameter parser and describe the purpose of the script. The example describes how to query a CNAME token.
parser = argparse.ArgumentParser(description="get cname token sample")

# Specify the command line parameters, including the region, bucket name, endpoint, and CNAME record.
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')
parser.add_argument('--cname', help='The name of the CNAME record that is mapped to the bucket.', required=True)

def main():
    # Parse the command line parameters to obtain the values entered by the user.
    args = parser.parse_args()

    # Obtain the access credentials from environment variables for identity authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configurations of the SDK to create a configuration object and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Specify the region attribute of the configuration object based on the command line parameters provided by the user.
    cfg.region = args.region

    # If a custom endpoint is provided, modify the endpoint parameter in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSSClient instance and allow the instance to interact with OSS.
    client = oss.Client(cfg)

    # Send a request to query the CNAME token of the bucket and the CNAME record.
    result = client.get_cname_token(oss.GetCnameTokenRequest(
            bucket=args.bucket, # The name of the bucket.
            cname=args.cname, # The name of the CNAME record for the custom domain name.
    ))

    # Display the status code of the operation result and other relevant information to check the request status and CNAME token details.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' cname: {result.cname_token.cname if hasattr(result.cname_token, "cname") else "Not set"},'
          f' token: {result.cname_token.token if hasattr(result.cname_token, "token") else "Not set"},'
          f' expire time: {result.cname_token.expire_time.strftime("%Y-%m-%dT%H:%M:%S.000Z") if hasattr(result.cname_token, "expire_time") else "Not set"},'
          f' bucket: {result.cname_token.bucket if hasattr(result.cname_token, "bucket") else "Not set"},'
          )

# Call the main function to start the processing logic when the script is directly run.
if __name__ == "__main__":
    main() # Specify the entry points in the functions of the script. The control program flow starts here.

CNAME kaydı ekleme

Aşağıdaki örnek kod, özel bir alan adını bir paketle eşlemek için kullanılan CNAME kaydının nasıl ekleneceğini gösterir.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command line parameter parser and describe the purpose of the script. The example describes how to add a CNAME record used to map a custom domain to a bucket.
parser = argparse.ArgumentParser(description="put cname sample")

# Specify the command line parameters, including the region, bucket name, endpoint, and custom domain name.
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')
parser.add_argument('--domain', help='The custom domain name.', required=True)

def main():
    # Parse the command line parameters to obtain the values entered by the user.
    args = parser.parse_args()

    # Obtain the access credentials from environment variables for identity authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configurations of the SDK to create a configuration object and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Specify the region attribute of the configuration object based on the command line parameters provided by the user.
    cfg.region = args.region

    # If a custom endpoint is provided, modify the endpoint parameter in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSSClient instance and allow the instance to interact with OSS.
    client = oss.Client(cfg)

    # Specify the SSL certificate parameters and associate the SSL certificate with the custom domain name.
    cert_id='493****-cn-hangzhou ' # The ID of the SSL certificate.
    certificate = '''-----BEGIN CERTIFICATE-----
MIIDhDCCAmwCCQCFs8ixARsyrDANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMC
**** -----END CERTIFICATE-----''' # The content of the SSL certificate.
    private_key = '''-----BEGIN CERTIFICATE-----
MIIDhDCCAmwCCQCFs8ixARsyrDANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMC
**** -----END CERTIFICATE-----''' # The content of the private key.
    previous_cert_id='493****-cn-hangzhou ' # The ID of the original SSL certificate.
    force = True # Forcibly overwrite the original SSL certificate.

    # Send a request to add a CNAME record used to map a custom domain to a bucket and associate the SSL certificate with the custom domain name.
    result = client.put_cname(oss.PutCnameRequest(
            bucket=args.bucket, # The name of the bucket.
            bucket_cname_configuration=oss.BucketCnameConfiguration(
                cname=oss.Cname(
                    domain=args.domain, # The custom domain name.
                    certificate_configuration=oss.CertificateConfiguration(
                        certificate=certificate, # The content of the SSL certificate.
                        private_key=private_key, # The content of the private key.
                        previous_cert_id=previous_cert_id, # The ID of the original SSL certificate.
                        force=force,  # Forcibly overwrite the original SSL certificate.
                        cert_id=cert_id, # The ID of the new SSL certificate.
                    ),
                ),
            ),
    ))

    # Display the status code of the operation result and request ID to check the request status.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          )

    """
    # Optional. If you want to delete the SSL certificate, please delete the description for the following code.
    result = client.put_cname(oss.PutCnameRequest(
            bucket=args.bucket,
            bucket_cname_configuration=oss.BucketCnameConfiguration(
                cname=oss.Cname(
                    domain=args.domain,
                    certificate_configuration=oss.CertificateConfiguration(
                        delete_certificate=True, # Delete the SSL certificate.
                    ),
                ),
            ),
    ))
    """

# Call the main function to start the processing logic when the script is directly run.
if __name__ == "__main__":
    main() # Specify the entry points in functions of the script. The control program flow starts here.

CNAME kayıtlarını listeleme

Aşağıdaki örnek kod, bir paketin CNAME kayıtlarının nasıl listeleneceğini gösterir:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command line parameter parser and describe the purpose of the script. The example describes how to list the CNAME records of a bucket.
parser = argparse.ArgumentParser(description="list cname sample")

# Specify the command line parameters, including the region, bucket name, and endpoint. The endpoint parameter is optional.
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 the command line parameters to obtain the values entered by the user.
    args = parser.parse_args()

    # Obtain the access credentials from environment variables for identity authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configurations of the SDK to create a configuration object and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Specify the region attribute of the configuration object based on the command line parameters provided by the user.
    cfg.region = args.region

    # If a custom endpoint is provided, modify the endpoint parameter in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSSClient instance and allow the instance to interact with OSS.
    client = oss.Client(cfg)

    # Send a request to list the CNAME records of the bucket.
    result = client.list_cname(oss.ListCnameRequest(
            bucket=args.bucket, # The name of the bucket.
    ))

    # Display the status code of the operation result, the request ID, and other relevant information to check the request status and CNAME records.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' bucket: {result. Bucket},' # The name of the bucket.
          f' owner: {result.owner},' # The owner of the bucket.
          )

    # If CNAME records exist, traverse and display the details of each CNAME record.
    if result.cnames:
        for r in result.cnames:
            # Display the domain name, last modified time, status, and SSL certificate information (if any) of the CNAME record.
            certificate_info = (f"fingerprint: {r.certificate.fingerprint}, "
                                f"valid start date: {r.certificate.valid_start_date}, "
                                f"valid end date: {r.certificate.valid_end_date}, "
                                f"type: {r.certificate.type}, "
                                f"cert id: {r.certificate.cert_id}, "
                                f"status: {r.certificate.status}, "
                                f"creation date: {r.certificate.creation_date}") if r.certificate else "No certificate"
            print(f'domain: {r.domain}, '
                  f'last modified: {r.last_modified}, '
                  f'status: {r.status}, '
                  f'certificate: {certificate_info}'
                  )

# Call the main function to start the processing logic when the script is directly run.
if __name__ == "__main__":
    main() # Specify the entry points in the functions of the script. The control program flow starts here.

CNAME kaydını silme

Aşağıdaki örnek kod, özel bir alan adını bir paketle eşlemek için kullanılan CNAME kaydının nasıl silineceğini gösterir:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command line parameter parser and describe the purpose of the script. The example describes how to delete a CNAME record used to map a custom domain to a bucket.
parser = argparse.ArgumentParser(description="delete cname sample")

# Specify the command line parameters, including the region, bucket name, endpoint, and custom domain name.
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')
parser.add_argument('--domain', help='The custom domain name.', required=True)

def main():
    # Parse the command line parameters to obtain the values entered by the user.
    args = parser.parse_args()

    # Obtain the access credentials from environment variables for identity authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configurations of the SDK to create a configuration object and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Specify the region attribute of the configuration object based on the command line parameters provided by the user.
    cfg.region = args.region

    # If a custom endpoint is provided, modify the endpoint parameter in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSSClient instance and allow the instance to interact with OSS.
    client = oss.Client(cfg)

    # Send a request to delete the CNAME record.
    result = client.delete_cname(oss.DeleteCnameRequest(
            bucket=args.bucket, # The name of the bucket.
            bucket_cname_configuration=oss.BucketCnameConfiguration(
                cname=oss.Cname(
                    domain=args.domain, # The custom domain name.
                ),
            ),
    ))

    # Display the status code of the operation result and request ID to check the request status.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          )

# Call the main function to start the processing logic when the script is directly run.
if __name__ == "__main__":
    main() # Specify the entry points in the functions of the script. The control program flow starts here.

Referanslar

  • Alan adı sahipliği doğrulaması için CNAME belirteci oluşturmada kullanılan tam örnek kod için create_cname_token.py adresini ziyaret edin.

  • CNAME belirtecini sorgulamada kullanılan tam örnek kod için get_cname_token.py adresini ziyaret edin.

  • CNAME kaydı eklemesinde kullanılan tam örnek kod için put_cname.py adresini ziyaret edin.

  • CNAME kayıtlarını listelemede kullanılan tam örnek kod için list_cname.py adresini ziyaret edin.

  • CNAME kaydını silmede kullanılan tam örnek kod için delete_cname.py adresini ziyaret edin.