The core module of Aliyun Python SDK providing authentication, request handling, and API communication for Alibaba Cloud services.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Core client functionality for API communication with Alibaba Cloud services. The AcsClient class handles authentication, request execution, retry logic, endpoint resolution, and response processing.
Creates an authenticated client for making API requests to Alibaba Cloud services with comprehensive configuration options.
class AcsClient:
def __init__(
self,
ak=None,
secret=None,
region_id="cn-hangzhou",
auto_retry=True,
max_retry_time=None,
user_agent=None,
port=80,
connect_timeout=None,
timeout=None,
public_key_id=None,
private_key=None,
session_period=3600,
credential=None,
debug=False,
verify=None,
pool_size=10,
proxy=None
):
"""
Initialize AcsClient with authentication and configuration.
Parameters:
- ak (str, optional): Access key ID for authentication
- secret (str, optional): Access key secret for authentication
- region_id (str): Target region ID, defaults to "cn-hangzhou"
- auto_retry (bool): Enable automatic retry on failures, defaults to True
- max_retry_time (int, optional): Maximum number of retry attempts
- user_agent (str, optional): Custom user agent string
- port (int): Connection port, defaults to 80
- connect_timeout (int, optional): Connection timeout in seconds
- timeout (int, optional): Request timeout in seconds
- public_key_id (str, optional): RSA public key ID for RSA authentication
- private_key (str, optional): RSA private key for RSA authentication
- session_period (int): Session duration for RSA authentication, defaults to 3600
- credential (object, optional): Credential object (AccessKeyCredential, StsTokenCredential, etc.)
- debug (bool): Enable debug logging, defaults to False
- verify (bool/str, optional): SSL certificate verification settings
- pool_size (int): HTTP connection pool size, defaults to 10
- proxy (dict, optional): Proxy configuration dictionary
"""Executes API requests with automatic authentication, endpoint resolution, and response handling.
def do_action_with_exception(self, acs_request):
"""
Execute an API request with automatic exception handling and parsing.
Parameters:
- acs_request (AcsRequest): The request object
Returns:
bytes: Response content from the API
Raises:
ClientException: For client-side errors
ServerException: For server-side errors with parsed error details
"""
def do_action(self, acs_request):
"""
DEPRECATED: Execute an API request and return the response.
Use do_action_with_exception() instead.
Parameters:
- acs_request (AcsRequest): The request object (RpcRequest, RoaRequest, or CommonRequest)
Returns:
bytes: Raw response content from the API
"""
def get_response(self, acs_request):
"""
Alternative method to execute requests (alias for implementation_of_do_action).
Parameters:
- acs_request (AcsRequest): The request object
Returns:
tuple: (status, headers, body, exception)
"""Methods for configuring client behavior and connection settings.
def set_user_agent(self, user_agent):
"""
Set custom user agent string for requests.
Parameters:
- user_agent (str): User agent string
"""
def set_max_retry_num(self, num):
"""
Set maximum retry attempts for failed requests.
Parameters:
- num (int): Maximum number of retries
"""
def set_auto_retry(self, auto_retry):
"""
Enable or disable automatic retry for failed requests.
Parameters:
- auto_retry (bool): Whether to enable auto retry
"""Debugging and logging capabilities for troubleshooting API communication.
def set_stream_logger(self, log_level=logging.DEBUG, logger_name='aliyunsdkcore', stream=None, format_string=None):
"""
Set up stream-based logging for debug output.
Parameters:
- log_level (int): Logging level, defaults to DEBUG
- logger_name (str): Logger name, defaults to 'aliyunsdkcore'
- stream: Output stream, defaults to None (stderr)
- format_string (str, optional): Custom log format string
"""
def set_file_logger(self, path, log_level=logging.DEBUG, logger_name='aliyunsdkcore'):
"""
Set up file-based logging for debug output.
Parameters:
- path (str): File path for log output
- log_level (int): Logging level, defaults to DEBUG
- logger_name (str): Logger name, defaults to 'aliyunsdkcore'
"""from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.auth.credentials import AccessKeyCredential
# Using access key directly
client = AcsClient(
ak="your-access-key-id",
secret="your-access-key-secret",
region_id="cn-shanghai"
)
# Using credential object (recommended)
credential = AccessKeyCredential("your-access-key-id", "your-access-key-secret")
client = AcsClient(credential=credential, region_id="cn-shanghai")from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.auth.credentials import StsTokenCredential
# Advanced client configuration
credential = StsTokenCredential(
"sts-access-key-id",
"sts-access-key-secret",
"sts-token"
)
client = AcsClient(
credential=credential,
region_id="cn-beijing",
timeout=30,
connect_timeout=10,
auto_retry=True,
max_retry_time=3, # Note: use set_max_retry_num() method to change after init
debug=True,
pool_size=20,
proxy={
'http': 'http://proxy.example.com:8080',
'https': 'https://proxy.example.com:8080'
}
)from aliyunsdkcore.request import CommonRequest
from aliyunsdkcore.acs_exception.exceptions import ClientException, ServerException
try:
request = CommonRequest()
request.set_method("POST")
request.set_domain("ecs.cn-hangzhou.aliyuncs.com")
request.set_version("2014-05-26")
request.set_action_name("DescribeInstances")
# Execute with recommended method
response = client.do_action_with_exception(request)
response_data = response.decode('utf-8')
# Or use deprecated method (not recommended)
# response = client.do_action(request)
except ClientException as e:
print(f"Client Error: {e.get_error_code()} - {e.get_error_msg()}")
except ServerException as e:
print(f"Server Error: {e.get_error_code()} - {e.get_error_msg()}")
print(f"HTTP Status: {e.get_http_status()}")
print(f"Request ID: {e.get_request_id()}")Install with Tessl CLI
npx tessl i tessl/pypi-aliyun-python-sdk-core