0
# Client Management
1
2
Core client functionality for API communication with Alibaba Cloud services. The `AcsClient` class handles authentication, request execution, retry logic, endpoint resolution, and response processing.
3
4
## Capabilities
5
6
### Client Initialization
7
8
Creates an authenticated client for making API requests to Alibaba Cloud services with comprehensive configuration options.
9
10
```python { .api }
11
class AcsClient:
12
def __init__(
13
self,
14
ak=None,
15
secret=None,
16
region_id="cn-hangzhou",
17
auto_retry=True,
18
max_retry_time=None,
19
user_agent=None,
20
port=80,
21
connect_timeout=None,
22
timeout=None,
23
public_key_id=None,
24
private_key=None,
25
session_period=3600,
26
credential=None,
27
debug=False,
28
verify=None,
29
pool_size=10,
30
proxy=None
31
):
32
"""
33
Initialize AcsClient with authentication and configuration.
34
35
Parameters:
36
- ak (str, optional): Access key ID for authentication
37
- secret (str, optional): Access key secret for authentication
38
- region_id (str): Target region ID, defaults to "cn-hangzhou"
39
- auto_retry (bool): Enable automatic retry on failures, defaults to True
40
- max_retry_time (int, optional): Maximum number of retry attempts
41
- user_agent (str, optional): Custom user agent string
42
- port (int): Connection port, defaults to 80
43
- connect_timeout (int, optional): Connection timeout in seconds
44
- timeout (int, optional): Request timeout in seconds
45
- public_key_id (str, optional): RSA public key ID for RSA authentication
46
- private_key (str, optional): RSA private key for RSA authentication
47
- session_period (int): Session duration for RSA authentication, defaults to 3600
48
- credential (object, optional): Credential object (AccessKeyCredential, StsTokenCredential, etc.)
49
- debug (bool): Enable debug logging, defaults to False
50
- verify (bool/str, optional): SSL certificate verification settings
51
- pool_size (int): HTTP connection pool size, defaults to 10
52
- proxy (dict, optional): Proxy configuration dictionary
53
"""
54
```
55
56
### Request Execution
57
58
Executes API requests with automatic authentication, endpoint resolution, and response handling.
59
60
```python { .api }
61
def do_action_with_exception(self, acs_request):
62
"""
63
Execute an API request with automatic exception handling and parsing.
64
65
Parameters:
66
- acs_request (AcsRequest): The request object
67
68
Returns:
69
bytes: Response content from the API
70
71
Raises:
72
ClientException: For client-side errors
73
ServerException: For server-side errors with parsed error details
74
"""
75
76
def do_action(self, acs_request):
77
"""
78
DEPRECATED: Execute an API request and return the response.
79
Use do_action_with_exception() instead.
80
81
Parameters:
82
- acs_request (AcsRequest): The request object (RpcRequest, RoaRequest, or CommonRequest)
83
84
Returns:
85
bytes: Raw response content from the API
86
"""
87
88
def get_response(self, acs_request):
89
"""
90
Alternative method to execute requests (alias for implementation_of_do_action).
91
92
Parameters:
93
- acs_request (AcsRequest): The request object
94
95
Returns:
96
tuple: (status, headers, body, exception)
97
"""
98
```
99
100
### Configuration Management
101
102
Methods for configuring client behavior and connection settings.
103
104
```python { .api }
105
def set_user_agent(self, user_agent):
106
"""
107
Set custom user agent string for requests.
108
109
Parameters:
110
- user_agent (str): User agent string
111
"""
112
113
def set_max_retry_num(self, num):
114
"""
115
Set maximum retry attempts for failed requests.
116
117
Parameters:
118
- num (int): Maximum number of retries
119
"""
120
121
def set_auto_retry(self, auto_retry):
122
"""
123
Enable or disable automatic retry for failed requests.
124
125
Parameters:
126
- auto_retry (bool): Whether to enable auto retry
127
"""
128
```
129
130
### Debug and Logging
131
132
Debugging and logging capabilities for troubleshooting API communication.
133
134
```python { .api }
135
def set_stream_logger(self, log_level=logging.DEBUG, logger_name='aliyunsdkcore', stream=None, format_string=None):
136
"""
137
Set up stream-based logging for debug output.
138
139
Parameters:
140
- log_level (int): Logging level, defaults to DEBUG
141
- logger_name (str): Logger name, defaults to 'aliyunsdkcore'
142
- stream: Output stream, defaults to None (stderr)
143
- format_string (str, optional): Custom log format string
144
"""
145
146
def set_file_logger(self, path, log_level=logging.DEBUG, logger_name='aliyunsdkcore'):
147
"""
148
Set up file-based logging for debug output.
149
150
Parameters:
151
- path (str): File path for log output
152
- log_level (int): Logging level, defaults to DEBUG
153
- logger_name (str): Logger name, defaults to 'aliyunsdkcore'
154
"""
155
```
156
157
## Usage Examples
158
159
### Basic Client Setup
160
161
```python
162
from aliyunsdkcore.client import AcsClient
163
from aliyunsdkcore.auth.credentials import AccessKeyCredential
164
165
# Using access key directly
166
client = AcsClient(
167
ak="your-access-key-id",
168
secret="your-access-key-secret",
169
region_id="cn-shanghai"
170
)
171
172
# Using credential object (recommended)
173
credential = AccessKeyCredential("your-access-key-id", "your-access-key-secret")
174
client = AcsClient(credential=credential, region_id="cn-shanghai")
175
```
176
177
### Advanced Configuration
178
179
```python
180
from aliyunsdkcore.client import AcsClient
181
from aliyunsdkcore.auth.credentials import StsTokenCredential
182
183
# Advanced client configuration
184
credential = StsTokenCredential(
185
"sts-access-key-id",
186
"sts-access-key-secret",
187
"sts-token"
188
)
189
190
client = AcsClient(
191
credential=credential,
192
region_id="cn-beijing",
193
timeout=30,
194
connect_timeout=10,
195
auto_retry=True,
196
max_retry_time=3, # Note: use set_max_retry_num() method to change after init
197
debug=True,
198
pool_size=20,
199
proxy={
200
'http': 'http://proxy.example.com:8080',
201
'https': 'https://proxy.example.com:8080'
202
}
203
)
204
```
205
206
### Request Execution with Error Handling
207
208
```python
209
from aliyunsdkcore.request import CommonRequest
210
from aliyunsdkcore.acs_exception.exceptions import ClientException, ServerException
211
212
try:
213
request = CommonRequest()
214
request.set_method("POST")
215
request.set_domain("ecs.cn-hangzhou.aliyuncs.com")
216
request.set_version("2014-05-26")
217
request.set_action_name("DescribeInstances")
218
219
# Execute with recommended method
220
response = client.do_action_with_exception(request)
221
response_data = response.decode('utf-8')
222
223
# Or use deprecated method (not recommended)
224
# response = client.do_action(request)
225
226
except ClientException as e:
227
print(f"Client Error: {e.get_error_code()} - {e.get_error_msg()}")
228
except ServerException as e:
229
print(f"Server Error: {e.get_error_code()} - {e.get_error_msg()}")
230
print(f"HTTP Status: {e.get_http_status()}")
231
print(f"Request ID: {e.get_request_id()}")
232
```