### Install All Huawei Cloud SDKs from Source Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Install the `huaweicloudsdkall` package from its source code. ```bash cd huaweicloudsdkall-${version} python setup.py install ``` -------------------------------- ### Install VPC Management Library from Source Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Install the VPC management library for Huawei Cloud Python SDK from its source code. ```bash # Install the VPC management library cd huaweicloudsdkvpc-${version} python setup.py install ``` -------------------------------- ### Install All Huawei Cloud SDKs with Pip Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Install the `huaweicloudsdkall` package using pip to get all supported SDK service packages. ```bash pip install huaweicloudsdkall ``` -------------------------------- ### Install VPC Management Library with Pip Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Use pip to install the VPC management library for Huawei Cloud Python SDK. ```bash # Install the VPC management library pip install huaweicloudsdkvpc ``` -------------------------------- ### Initialize VPC Client with Custom Settings Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README_CN.md This example demonstrates initializing the VPC client with custom authentication, region, HTTP configurations, and logging settings. It includes configuring IAM endpoint, SSL verification, timeouts, proxy, and HTTP handlers. ```python # coding: utf-8 import os import logging from huaweicloudsdkcore.auth.credentials import BasicCredentials from huaweicloudsdkcore.http.http_config import HttpConfig from huaweicloudsdkcore.http.http_handler import HttpHandler from huaweicloudsdkvpc.v2 import VpcClient, ListVpcsRequest from huaweicloudsdkvpc.v2.region.vpc_region import VpcRegion from huaweicloudsdkcore.exceptions import exceptions if __name__ == "__main__": # 配置认证信息 # 请勿将认证信息硬编码到代码中,有安全风险 # 可通过环境变量等方式配置认证信息,参考2.4认证信息管理章节 # 如果未填写project_id,SDK会自动调用IAM服务查询所在region对应的项目id credentials = BasicCredentials(os.getenv("HUAWEICLOUD_SDK_AK"), os.getenv("HUAWEICLOUD_SDK_SK"), project_id="{yourProjectId string}") \ .with_iam_endpoint("https://iam.cn-north-4.myhuaweicloud.com") # 配置SDK内置的IAM服务地址 # 使用默认配置 http_config = HttpConfig.get_default_config() # 配置是否忽略SSL证书校验, 默认不忽略 http_config.ignore_ssl_verification = True # 配置CA证书文件 http_config.ssl_ca_cert = '/path/to/certfile' # 默认连接超时时间为60秒,读取超时时间为120秒,可根据需要配置 http_config.timeout = (60, 120) # 根据需要配置网络代理 # 请根据实际情况替换示例中的代理协议、地址和端口号 http_config.proxy_protocol = 'http' http_config.proxy_host = 'proxy.huaweicloud.com' http_config.proxy_port = 80 # 如果代理需要认证,请配置用户名和密码 http_config.proxy_user = os.getenv("PROXY_USERNAME") http_config.proxy_password = os.getenv("PROXY_PASSWORD") # 注册监听器用于打印原始的请求和响应信息, 请勿用于生产环境 def response_handler(**kwargs): response = kwargs.get("response") request = response.request info = "> Request %s %s HTTP/1.1" % (request.method, request.path_url) + "\n" if len(request.headers) != 0: info = info + "> Headers:" + "\n" for each in request.headers: info = info + " %s: %s" % (each, request.headers[each]) + "\n" info = info + "> Body: %s" % request.body + "\n\n" info = info + "< Response HTTP/1.1 %s " % response.status_code + "\n" if len(response.headers) != 0: info = info + "< Headers:" + "\n" for each in response.headers: info = info + " %s: %s" % (each, response.headers[each],) + "\n" info = info + "< Body: %s" % response.content print(info) http_handler = HttpHandler().add_response_handler(response_handler) # 创建服务客户端 client = (VpcClient.new_builder() .with_credentials(credentials) # 配置认证信息 .with_region(VpcRegion.value_of("cn-north-4")) # 配置地区, 如果地区不存在会抛出KeyError .with_http_config(http_config) # HTTP配置 .with_stream_log(log_level=logging.INFO) # 配置请求日志输出到控制台 .with_file_log(path="test.log", log_level=logging.INFO) # 配置请求日志输出到文件 .with_http_handler(http_handler) # 配置HTTP监听器 .build()) # 发送请求并获取响应 try: request = ListVpcsRequest() response = client.list_vpcs(request) print(response) except exceptions.ClientRequestException as e: print(e.status_code) print(e.request_id) print(e.error_code) print(e.error_msg) ``` -------------------------------- ### Send Request and Print Response in Python Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README_CN.md Demonstrates how to initialize a request object and send it using a client, then print the raw response. This is a basic example for interacting with Huawei Cloud services. ```python # 初始化请求,以调用接口 ListVpcs 为例 request = ListVpcsRequest(limit=1) response = client.list_vpcs(request) print(response) ``` -------------------------------- ### Access Log Configuration Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Demonstrates how to enable and configure access logs for the SDK, allowing output to files or the console. Includes examples for `with_file_log` and `with_stream_log`. ```APIDOC ## Access Log Configuration SDK supports printing access logs, which can be enabled by manual configuration. The logs can be output to the console or specified files. Initialize a specified service client instance, taking `VpcClient` for example: ```python from huaweicloudsdkvpc.v3 import VpcClient import logging client = ( VpcClient.new_builder() .with_file_log(path="test.log", log_level=logging.INFO) # Write log files .with_stream_log(log_level=logging.INFO) # Write log to console .build() ) ``` **Parameters for `with_file_log`:** - `path` (string): The path to the log file. - `log_level` (logging level): The logging level, defaults to `INFO`. - `max_bytes` (int): The size of a single log file in bytes, defaults to 10485760. - `backup_count` (int): The number of backup log files, defaults to 5. **Parameters for `with_stream_log`:** - `stream` (object): The stream object to write logs to, defaults to `sys.stdout`. - `log_level` (logging level): The logging level, defaults to `INFO`. After enabling logs, the SDK will print access logs by default. Every request will be recorded to the console in the following format: ```text 2020-06-16 10:44:02,019 4568 HuaweiCloud-SDK http_handler.py 28 INFO "GET https://vpc.cn-north-1.myhuaweicloud.com/v1/0904f9e1f100d2932f94c01f9aa1cfd7/vpcs" 200 11 0:00:00.543430 b5c927ffdab8401e772e70aa49972037 ``` The format of the access log is: ```python %(asctime)s %(thread)d %(name)s %(filename)s %(lineno)d %(levelname)s %(message)s ``` ``` -------------------------------- ### Profile Configuration for AK/SK Auth Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Example INI file content for basic and global AK/SK authentication using profile files. ```ini [basic] ak = your_ak sk = your_sk [global] ak = your_ak sk = your_sk ``` -------------------------------- ### Profile Configuration for IdP/IdTokenFile Auth Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Example INI file content for basic and global IdP/IdTokenFile authentication, including optional parameters. ```ini [basic] idp_id = your_idp_id id_token_file = /some_path/your_token_file project_id = your_project_id [global] idp_id = your_idp_id id_token_file = /some_path/your_token_file domainId = your_domain_id ``` -------------------------------- ### Send Request and Print Response Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Initialize a request and send it using the client. The response is then printed. This example uses the ListVpcs interface. ```python # Initialize a request and print response, take interface of ListVpcs for example request = ListVpcsRequest(limit=1) response = client.list_vpcs(request) print(response) ``` -------------------------------- ### Send Requests and Handle Responses Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Provides an example of sending a request and printing the response, using `ListVpcs` as an illustration. ```APIDOC ## Send Requests and Handle Responses ### Description This section demonstrates how to initiate a request to a Huawei Cloud service and process the response. The example uses the `ListVpcsRequest` and the `list_vpcs` method of the client. ### Method `client.list_vpcs(request)` ### Parameters #### Request Body - **request** (object) - Required - An instance of `ListVpcsRequest` containing request parameters. - **limit** (int) - Optional - Limits the number of VPCs returned. ### Request Example ```python # Initialize a request and print response, take interface of ListVpcs for example request = ListVpcsRequest(limit=1) response = client.list_vpcs(request) print(response) ``` ### Response #### Success Response (200) The response object contains the data returned by the service. The exact structure depends on the API called. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Query VPC List with Huawei Cloud Python SDK Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md This example demonstrates how to query a list of VPCs in a specific region using the Huawei Cloud Python SDK. It is recommended to configure AK/SK via environment variables (`HUAWEICLOUD_SDK_AK`, `HUAWEICLOUD_SDK_SK`) for security, rather than hard-coding them. Ensure the VPC service is activated in the Huawei Cloud console if necessary. ```python # coding: utf-8 import os from huaweicloudsdkcore.auth.credentials import BasicCredentials from huaweicloudsdkvpc.v2 import ListVpcsRequest, VpcClient from huaweicloudsdkvpc.v2.region.vpc_region import VpcRegion from huaweicloudsdkcore.exceptions import exceptions if __name__ == "__main__": # Configure authentication # Do not hard-code authentication information into the code, as this may pose a security risk # Authentication can be configured through environment variables and other methods. Please refer to Chapter 2.4 Authentication Management credentials = BasicCredentials(os.getenv("HUAWEICLOUD_SDK_AK"), os.getenv("HUAWEICLOUD_SDK_SK")) # Create a service client client = VpcClient.new_builder() \ .with_credentials(credentials) \ .with_region(VpcRegion.value_of("cn-north-4")) \ .build() # Send the request and get the response try: request = ListVpcsRequest() response = client.list_vpcs(request) print(response) except exceptions.ClientRequestException as e: print(e.status_code) print(e.request_id) print(e.error_code) print(e.error_msg) ``` -------------------------------- ### Retrieve AK/SK Credentials from Profile Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Use ProfileCredentialProvider to get basic and global AK/SK credentials from a profile file. ```python from huaweicloudsdkcore.auth.provider import ProfileCredentialProvider # basic basic_provider = ProfileCredentialProvider.get_basic_credential_profile_provider() basic_cred = basic_provider.get_credentials() # global global_provider = ProfileCredentialProvider.get_global_credential_profile_provider() global_cred = global_provider.get_credentials() ``` -------------------------------- ### Get Credentials from Instance Metadata Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Obtains basic and global credentials from the instance's metadata service. Ensure the instance has the necessary permissions. ```python from huaweicloudsdkcore.auth.provider import MetadataCredentialProvider # basic basic_provider = MetadataCredentialProvider.get_basic_credential_metadata_provider() basic_cred = basic_provider.get_credentials() # global global_provider = MetadataCredentialProvider.get_global_credential_metadata_provider() global_cred = global_provider.get_credentials() ``` -------------------------------- ### Upload and Download Image Files Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Example of uploading an image file for watermarking and then downloading the resulting watermarked image. Requires opening files in binary read mode and using FormFile for uploads. ```python # coding: utf-8 import os from huaweicloudsdkcore.auth.credentials import BasicCredentials from huaweicloudsdkcore.exceptions import exceptions from huaweicloudsdkcore.http.http_config import HttpConfig from huaweicloudsdkcore.http.formdata import FormFile from huaweicloudsdksc.v1 import * def create_image_watermark(client): try: request = CreateImageWatermarkRequest() # Open the file in mode "rb", create a Formfile object. image_file = FormFile(open("demo.jpg", "rb")) body = CreateImageWatermarkRequestBody(file=image_file, blind_watermark="test_watermark") request.body = body response = client.create_image_watermark(request) image_file.close() # Define the method of downloading files. def save(stream): with open("result.jpg", "wb") as f: f.write(stream.content) # Download the file. response.consume_download_stream(save) except exceptions.ClientRequestException as e: print(e.status_code) print(e.request_id) print(e.error_code) print(e.error_msg) if __name__ == "__main__": ak = os.getenv("HUAWEICLOUD_SDK_AK") sk = os.getenv("HUAWEICLOUD_SDK_SK") endpoint = "{your endpoint}" project_id = "{your project id}" config = HttpConfig.get_default_config() config.ignore_ssl_verification = True credentials = BasicCredentials(ak, sk, project_id) dsc_client = DscClient.new_builder() \ .with_http_config(config) \ .with_credentials(credentials) \ .with_endpoint(endpoint) \ .build() create_image_watermark(dsc_client) ``` -------------------------------- ### Retrieve AK/SK Credentials from Environment Variables Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Use EnvCredentialProvider to get basic and global AK/SK credentials configured via environment variables. ```python from huaweicloudsdkcore.auth.provider import EnvCredentialProvider # basic basic_provider = EnvCredentialProvider.get_basic_credential_env_provider() basic_cred = basic_provider.get_credentials() # global global_provider = EnvCredentialProvider.get_global_credential_env_provider() global_cred = global_provider.get_credentials() ``` -------------------------------- ### Get Credentials from Provider Chain Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Obtains basic and global credentials by trying Environment Variables, Profile, Metadata, and Pod Identity in order. This is the default behavior when initializing a client without explicit credentials. ```python from huaweicloudsdkcore.auth.provider import CredentialProviderChain # basic basic_chain = CredentialProviderChain.get_basic_credential_provider_chain() basic_cred = basic_chain.get_credentials() # global global_chain = CredentialProviderChain.get_global_credential_provider_chain() global_cred = global_chain.get_credentials() ``` -------------------------------- ### Initialize Service Client for Cloud Service Alliance Scenarios Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Demonstrates how to initialize a service client, such as VpcClient, for use in specific regions and with appropriate credentials. Requires setting the endpoint and providing authentication details. ```python # Specify the endpoint, take the endpoint of VPC service in region of eu-west-101 for example endpoint = "https://vpc.eu-west-101.myhuaweicloud.com" # Initialize the credentials, you should provide project_id or domain_id in this way, take initializing BasicCredentials for example ak = os.getenv("HUAWEICLOUD_SDK_AK") sk = os.getenv("HUAWEICLOUD_SDK_SK") project_id = "{your projectId string}" basic_credentials = BasicCredentials(ak, sk, project_id) # Initialize specified service client instance, take initializing the regional service VPC's VpcClient for example client = VpcClient.new_builder() \ .with_credentials(basic_credentials) \ .with_endpoint(endpoint) \ .build() ``` -------------------------------- ### Initialize VPC Client with Default HTTP Configuration Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Demonstrates initializing a VPC client using the default HTTP configuration. Ensure `VpcClient` is imported. ```python from huaweicloudsdkcore.http.http_config import HttpConfig # Use default configuration http_config = HttpConfig.get_default_config() client = VpcClient.new_builder() \ .with_http_config(http_config) \ .build() ``` -------------------------------- ### Retrieve IdP/IdTokenFile Credentials from Profile Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Use ProfileCredentialProvider to get basic IdP/IdTokenFile credentials from a profile file. ```python from huaweicloudsdkcore.auth.provider import ProfileCredentialProvider # basic basic_provider = ProfileCredentialProvider.get_basic_credential_profile_provider() basic_cred = basic_provider.get_credentials() ``` -------------------------------- ### Initialize VPC Client with Default Configuration Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README_CN.md This snippet shows how to initialize the VPC client using default HTTP configurations. Ensure necessary imports are present. ```python from huaweicloudsdkcore.http.http_config import HttpConfig # 使用默认配置 http_config = HttpConfig.get_default_config() client = VpcClient.new_builder() \ .with_http_config(http_config) \ .build() ``` -------------------------------- ### Get Global Credentials from Profile Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Retrieves global credentials using the default profile credential provider. ```python from huaweicloudsdkcore.auth.provider import ProfileCredentialProvider global_provider = ProfileCredentialProvider.get_global_credential_profile_provider() global_cred = global_provider.get_credentials() ``` -------------------------------- ### Configure VPC Client and List VPCs Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md This snippet shows how to configure authentication, HTTP settings, and create a VPC client. It then demonstrates sending a request to list VPCs and handling potential exceptions. Ensure authentication details are not hard-coded and are managed securely. ```python # coding: utf-8 import os import logging from huaweicloudsdkcore.auth.credentials import BasicCredentials from huaweicloudsdkcore.http.http_config import HttpConfig from huaweicloudsdkcore.http.http_handler import HttpHandler from huaweicloudsdkvpc.v2 import VpcClient, ListVpcsRequest from huaweicloudsdkvpc.v2.region.vpc_region import VpcRegion from huaweicloudsdkcore.exceptions import exceptions if __name__ == "__main__": # Configure authentication # Do not hard-code authentication information into the code, as this may pose a security risk # Authentication can be configured through environment variables and other methods. Please refer to Chapter 2.4 Authentication Management # If project_id is not filled in, the SDK will automatically call the IAM service to query the project id corresponding to the region. credentials = BasicCredentials(os.getenv("HUAWEICLOUD_SDK_AK"), os.getenv("HUAWEICLOUD_SDK_SK"), project_id="{yourProjectId string}") \ .with_iam_endpoint("https://iam.cn-north-4.myhuaweicloud.com") # Configure the SDK built-in IAM service endpoint # Use default configuration http_config = HttpConfig.get_default_config() # Configure whether to ignore the SSL certificate verification, default is false http_config.ignore_ssl_verification = True # Configure CA certificate file http_config.ssl_ca_cert = '/path/to/certfile' # The default connection timeout is 60 seconds, the default read timeout is 120 seconds http_config.timeout = (60, 120) # Configure proxy as needed # Replace the proxy protocol, host and port in the example according to the actual situation http_config.proxy_protocol = 'http' http_config.proxy_host = 'proxy.huaweicloud.com' http_config.proxy_port = 80 # Configure the username and password if the proxy requires authentication http_config.proxy_user = os.getenv("PROXY_USERNAME") http_config.proxy_password = os.getenv("PROXY_PASSWORD") # The HTTP handler is used to print the request and response, do not use it in the production environment def response_handler(**kwargs): response = kwargs.get("response") request = response.request info = "> Request %s %s HTTP/1.1" % (request.method, request.path_url) + "\n" if len(request.headers) != 0: info = info + "> Headers:" + "\n" for each in request.headers: info = info + " %s: %s" % (each, request.headers[each]) + "\n" info = info + "> Body: %s" % request.body + "\n\n" info = info + "< Response HTTP/1.1 %s " % response.status_code + "\n" if len(response.headers) != 0: info = info + "< Headers:" + "\n" for each in response.headers: info = info + " %s: %s" % (each, response.headers[each],) + "\n" info = info + "< Body: %s" % response.content print(info) http_handler = HttpHandler().add_response_handler(response_handler) # Create a service client client = (VpcClient.new_builder() .with_credentials(credentials) # Configure authentication .with_region(VpcRegion.value_of("cn-north-4")) # Configure region, it will throw a KeyError if the region does not exist .with_http_config(http_config) # Configure HTTP .with_stream_log(log_level=logging.INFO) # Configure request log output to console .with_file_log(path="test.log", log_level=logging.INFO) # Configure request log output to file .with_http_handler(http_handler) # Configure HTTP handler .build()) # Send the request and get the response try: request = ListVpcsRequest() response = client.list_vpcs(request) print(response) except exceptions.ClientRequestException as e: print(e.status_code) print(e.request_id) print(e.error_code) print(e.error_msg) ``` -------------------------------- ### Get Response Object Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Explains how to convert the default JSON string response into a Python object using `to_json_object()`. ```APIDOC ## Get Response Object ### Description This section describes how to obtain a structured Python object from the response of an API call, instead of the default JSON string. This is achieved using the `to_json_object()` method, available in SDK versions 3.0.34-rc and later. ### Method `response.to_json_object()` ### Parameters #### Request Body - **request** (object) - Required - An instance of `ListVpcsRequest` containing request parameters. - **limit** (int) - Optional - Limits the number of VPCs returned. ### Request Example ```python request = ListVpcsRequest(limit=1) # original response json string response = client.list_vpcs(request) print(response) # response object response_obj = response.to_json_object() print(response_obj["vpcs"]) ``` ### Response #### Success Response (200) The `response_obj` will be a Python dictionary representing the JSON response, allowing direct access to its elements. #### Response Example ```json { "vpcs": [ { "example": "vpc object details" } ] } ``` ``` -------------------------------- ### Initialize Client with Specific Region (Recommended) Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README_CN.md Initializes a service client by specifying the region. This is the recommended approach as it supports automatic retrieval of project ID and domain ID. ```python import os # 增加region依赖 from huaweicloudsdkiam.v3.region.iam_region import IamRegion # 初始化客户端认证信息,使用当前客户端初始化方式可不填 project_id/domain_id # 以初始化 GlobalCredentials 为例 ak = os.getenv("HUAWEICLOUD_SDK_AK") sk = os.getenv("HUAWEICLOUD_SDK_SK") global_credentials = GlobalCredentials(ak, sk) # 初始化指定云服务的客户端 {Service}Client # 以初始化 Global 级服务 IAM 的 IamClient 为例 client = IamClient.new_builder() \ .with_http_config(config) \ .with_credentials(global_credentials) \ .with_region(IamRegion.CN_NORTH_4) \ .build() ``` -------------------------------- ### Initialize with Temporary AK/SK Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Use this to initialize credentials with temporary AK/SK and a security token. Obtain temporary credentials via token or agency as per the documentation. ```python # Regional services ak = os.getenv("HUAWEICLOUD_SDK_AK") sk = os.getenv("HUAWEICLOUD_SDK_SK") security_token = os.getenv("HUAWEICLOUD_SDK_SECURITY_TOKEN") project_id = "{your projectId string}" basic_credentials = BasicCredentials(ak, sk, project_id).with_security_token(security_token) # Global services ak = os.getenv("HUAWEICLOUD_SDK_AK") sk = os.getenv("HUAWEICLOUD_SDK_SK") security_token = os.getenv("HUAWEICLOUD_SDK_SECURITY_TOKEN") domain_id = "{your domainId string}" global_credentials = GlobalCredentials(ak, sk, domain_id).with_security_token(security_token) ``` -------------------------------- ### Configure IdP/IdTokenFile Auth via Environment Variables (Windows) Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Set IdP ID, Id Token file path, and optional project/domain IDs for IdP/IdTokenFile authentication on Windows. ```shell set HUAWEICLOUD_SDK_IDP_ID=YOUR_IDP_ID set HUAWEICLOUD_SDK_ID_TOKEN_FILE=/some_path/your_token_file set HUAWEICLOUD_SDK_PROJECT_ID=YOUR_PROJECT_ID // For basic credentials, this parameter is required set HUAWEICLOUD_SDK_DOMAIN_ID=YOUR_DOMAIN_ID // For global credentials, this parameter is required ``` -------------------------------- ### Configure IdP/IdTokenFile Auth via Environment Variables (Linux) Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Set IdP ID, Id Token file path, and optional project/domain IDs for IdP/IdTokenFile authentication on Linux. ```shell export HUAWEICLOUD_SDK_IDP_ID=YOUR_IDP_ID export HUAWEICLOUD_SDK_ID_TOKEN_FILE=/some_path/your_token_file export HUAWEICLOUD_SDK_PROJECT_ID=YOUR_PROJECT_ID // For basic credentials, this parameter is required export HUAWEICLOUD_SDK_DOMAIN_ID=YOUR_DOMAIN_ID // For global credentials, this parameter is required ``` -------------------------------- ### Initialize with IdP ID and ID Token File Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Initialize credentials using an IdP ID and an ID token file for federated identity authentication. This method is suitable for obtaining tokens via OpenID Connect. ```python from huaweicloudsdkcore.auth.credentials import BasicCredentials, GlobalCredentials # Regional service basic_cred = BasicCredentials() \ .with_idp_id(idp_id) \ .with_id_token_file(id_token_file) \ .with_project_id(project_id) # Global service global_cred = GlobalCredentials() \ .with_idp_id(idp_id) \ .with_id_token_file(id_token_file) \ .with_domain_id(domain_id) ``` -------------------------------- ### Get Global Credential Provider Chain Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README_CN.md Retrieves the default chain for loading global credentials. Similar to the basic chain, it follows a specific order for credential discovery. ```python # global global_chain = CredentialProviderChain.get_global_credential_provider_chain() global_cred = global_chain.get_credentials() ``` -------------------------------- ### Get Credentials using Pod Identity Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Retrieves basic and global credentials using Pod Identity in CCE clusters. Requires SDK version 3.1.190 or later. ```python from huaweicloudsdkcore.auth.provider import PodIdentityCredentialProvider # basic basic_provider = PodIdentityCredentialProvider.get_basic() basic_cred = basic_provider.get_credentials() # global global_provider = PodIdentityCredentialProvider.get_global() global_provider = global_provider.get_credentials() ``` -------------------------------- ### Initialize with Permanent AK/SK Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Initialize credentials using permanent AK/SK. It is recommended to use AK/SK from an IAM user with minimal privileges due to security risks associated with the main account's AK/SK. ```python # Regional services ak = os.getenv("HUAWEICLOUD_SDK_AK") sk = os.getenv("HUAWEICLOUD_SDK_SK") project_id = "{your projectId string}" basic_credentials = BasicCredentials(ak, sk, project_id) # Global services ak = os.getenv("HUAWEICLOUD_SDK_AK") sk = os.getenv("HUAWEICLOUD_SDK_SK") domain_id = "{your domainId string}" global_credentials = GlobalCredentials(ak, sk, domain_id) ``` -------------------------------- ### Use Asynchronous Client Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Demonstrates the initialization and usage of the asynchronous client for non-blocking API calls. ```APIDOC ## Use Asynchronous Client ### Description This section guides on how to use the asynchronous client for making non-blocking API calls. It covers initializing the `VpcAsyncClient` and sending asynchronous requests, then retrieving the results. ### Method `VpcAsyncClient.new_builder()...build()` and `client.list_vpcs_async(request)` ### Parameters #### Request Body - **config** (object) - HTTP configuration. - **basic_credentials** (object) - Credentials for authentication. - **endpoint** (string) - The service endpoint URL. - **request** (object) - An instance of `ListVpcsRequest` containing request parameters. - **limit** (int) - Optional - Limits the number of VPCs returned. ### Request Example ```python # Initialize asynchronous client, take VpcAsyncClient for example client = VpcAsyncClient.new_builder() \ .with_http_config(config) \ .with_credentials(basic_credentials) \ .with_endpoint(endpoint) \ .build() # send asynchronous request request = ListVpcsRequest(limit=1) response = client.list_vpcs_async(request) # get asynchronous response print(response.result()) ``` ### Response #### Success Response The `response.result()` method returns the result of the asynchronous operation. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Get Region Information in Python Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README_CN.md Retrieve region information using `Region.value_of(region_id)`. The SDK searches for the region in environment variables, configuration files, and then in its predefined regions. An exception is raised if the region is not found. ```python from huaweicloudsdkecs.v2.region.ecs_region import EcsRegion region1 = EcsRegion.value_of("cn-north-1") region2 = EcsRegion.value_of("cn-north-9") ``` -------------------------------- ### Configure AK/SK Auth via Environment Variables (Windows) Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Set AccessKey and SecretKey as environment variables for AK/SK authentication on Windows systems. ```shell set HUAWEICLOUD_SDK_AK=YOUR_AK set HUAWEICLOUD_SDK_SK=YOUR_SK ``` -------------------------------- ### Get Basic Credential Provider Chain Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README_CN.md Retrieves the default chain for loading basic credentials. This chain attempts to load credentials from environment variables, configuration files, instance metadata, and container group identity in order. ```python from huaweicloudsdkcore.auth.provider import CredentialProviderChain # basic basic_chain = CredentialProviderChain.get_basic_credential_provider_chain() basic_cred = basic_chain.get_credentials() ``` -------------------------------- ### Get Response Object from JSON String Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Convert the default JSON string response to a Python object using the `to_json_object()` method. This allows for easier access to specific data within the response. Supported in version 3.0.34-rc or later. ```python request = ListVpcsRequest(limit=1) # original response json string response = client.list_vpcs(request) print(response) # response object response_obj = response.to_json_object() print(response_obj["vpcs"]) ``` -------------------------------- ### Initialize Service Client with Specified Region Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Initializes a service client using a specified region, which is the recommended approach. It allows for optional project or domain ID assignment during credential initialization. ```python import os # dependency for region module from huaweicloudsdkiam.v3.region.iam_region import IamRegion # Initialize the credentials, project_id or domain_id could be unassigned in this situation # Take initializing GlobalCredentials for example ak = os.getenv("HUAWEICLOUD_SDK_AK") sk = os.getenv("HUAWEICLOUD_SDK_SK") global_credentials = GlobalCredentials(ak, sk) # Initialize specified service client instance ``` -------------------------------- ### Get Response Object as JSON in Python Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README_CN.md Convert the SDK's JSON response into a Python dictionary-like object using the `to_json_object()` method. This allows for easier access to specific data fields within the response. Available from version 3.0.34-rc. ```python request = ListVpcsRequest(limit=1) # 原始响应Json response = client.list_vpcs(request) print(response) # 响应对象 response_obj = response.to_json_object() print(response_obj["vpcs"]) ``` -------------------------------- ### Configure File and Stream Access Logs Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Enable and configure access logging for the SDK client. Specify log file path, log level, file size, and backup count for file logging, or set the log level for console output. ```python client = (VpcClient.new_builder() .with_file_log(path="test.log", log_level=logging.INFO) # Write log files .with_stream_log(log_level=logging.INFO) # Write log to console .build()) ``` -------------------------------- ### Initialize Service Client with Specified Endpoint Source: https://github.com/huaweicloud/huaweicloud-sdk-python-v3/blob/master/README.md Initializes a service client by explicitly providing the endpoint URL, HTTP configuration, and basic credentials including project ID. Useful when the default region-based endpoint is not suitable. ```python # Specify the endpoint, take the endpoint of VPC service in region of cn-north-4 for example endpoint = "https://vpc.cn-north-4.myhuaweicloud.com" # Initialize the credentials, you should provide project_id or domain_id in this way, take initializing BasicCredentials for example ak = os.getenv("HUAWEICLOUD_SDK_AK") sk = os.getenv("HUAWEICLOUD_SDK_SK") project_id = "{your projectId string}" basic_credentials = BasicCredentials(ak, sk, project_id) # Initialize specified service client instance, take initializing the regional service VPC's VpcClient for example client = VpcClient.new_builder() \ .with_http_config(config) \ .with_credentials(basic_credentials) \ .with_endpoint(endpoint) \ .build() ```