0
# Data Models
1
2
Base model class and service-specific request/response models providing JSON serialization, data validation, and structured data handling for all API interactions. All models inherit from `AbstractModel` and support automatic serialization.
3
4
## Capabilities
5
6
### Abstract Model Base Class
7
8
Foundation class providing JSON serialization, deserialization, and data validation capabilities for all request and response objects in the SDK.
9
10
```python { .api }
11
class AbstractModel:
12
def __init__(self):
13
"""
14
Initialize base model with empty attributes.
15
All model properties are set to None by default.
16
"""
17
18
def to_json_string(self, indent: int = None) -> str:
19
"""
20
Serialize model to JSON string.
21
22
Parameters:
23
- indent (int, optional): JSON indentation for pretty printing
24
25
Returns:
26
str: JSON string representation of the model
27
"""
28
29
def from_json_string(self, json_string: str):
30
"""
31
Deserialize JSON string to populate model attributes.
32
33
Parameters:
34
- json_string (str): JSON string to deserialize
35
36
Returns:
37
AbstractModel: Self for method chaining
38
"""
39
40
def _serialize(self) -> dict:
41
"""
42
Internal method to convert model to dictionary.
43
44
Returns:
45
dict: Dictionary representation excluding None values
46
"""
47
```
48
49
**Basic Model Usage:**
50
51
```python
52
from tencentcloud.cvm.v20170312 import models
53
54
# Create request model
55
request = models.DescribeInstancesRequest()
56
request.InstanceIds = ["ins-12345678", "ins-87654321"]
57
request.Limit = 20
58
request.Offset = 0
59
60
# Serialize to JSON
61
json_str = request.to_json_string(indent=2)
62
print(json_str)
63
64
# Deserialize from JSON
65
new_request = models.DescribeInstancesRequest()
66
new_request.from_json_string(json_str)
67
```
68
69
### Request Models
70
71
Structured input objects for API calls, providing type safety and parameter validation. All request models follow the naming pattern `{Action}Request`.
72
73
#### Common Request Patterns
74
75
**Pagination Support:**
76
77
```python { .api }
78
# Common pagination parameters across many request models
79
class PaginatedRequest(AbstractModel):
80
def __init__(self):
81
self.Limit: int = None # Maximum items to return (usually 20-100)
82
self.Offset: int = None # Starting position for pagination
83
```
84
85
**Filtering Support:**
86
87
```python { .api }
88
class Filter(AbstractModel):
89
def __init__(self):
90
"""
91
Filter criteria for query operations.
92
"""
93
self.Name: str = None # Filter field name
94
self.Values: list = None # List of filter values
95
96
# Used in many describe requests
97
class FilteredRequest(AbstractModel):
98
def __init__(self):
99
self.Filters: list = None # List of Filter objects
100
```
101
102
**Placement Information:**
103
104
```python { .api }
105
class Placement(AbstractModel):
106
def __init__(self):
107
"""
108
Resource placement configuration.
109
"""
110
self.Zone: str = None # Availability zone
111
self.ProjectId: int = None # Project ID
112
self.HostIds: list = None # Dedicated host IDs
113
```
114
115
#### CVM Request Models
116
117
```python { .api }
118
class RunInstancesRequest(AbstractModel):
119
def __init__(self):
120
"""Request to create and launch CVM instances."""
121
self.ImageId: str = None # System image ID
122
self.InstanceType: str = None # Instance specification
123
self.Placement: Placement = None # Placement configuration
124
self.InstanceCount: int = None # Number of instances
125
self.InstanceName: str = None # Instance name
126
self.LoginSettings: LoginSettings = None # Login configuration
127
self.SecurityGroupIds: list = None # Security group IDs
128
self.VirtualPrivateCloud: VirtualPrivateCloud = None # VPC configuration
129
self.SystemDisk: SystemDisk = None # System disk configuration
130
self.DataDisks: list = None # Data disk configurations
131
self.InternetAccessible: InternetAccessible = None # Internet access
132
self.InstanceChargeType: str = None # Billing method
133
self.TagSpecification: list = None # Resource tags
134
135
class DescribeInstancesRequest(AbstractModel):
136
def __init__(self):
137
"""Request to query CVM instance information."""
138
self.InstanceIds: list = None # Specific instance IDs
139
self.Filters: list = None # Filter criteria
140
self.Offset: int = None # Pagination offset
141
self.Limit: int = None # Maximum results
142
143
class TerminateInstancesRequest(AbstractModel):
144
def __init__(self):
145
"""Request to terminate CVM instances."""
146
self.InstanceIds: list = None # Instance IDs to terminate
147
```
148
149
#### CBS Request Models
150
151
```python { .api }
152
class CreateDisksRequest(AbstractModel):
153
def __init__(self):
154
"""Request to create cloud block storage disks."""
155
self.DiskType: str = None # Disk type (CLOUD_BASIC, CLOUD_PREMIUM, CLOUD_SSD)
156
self.DiskSize: int = None # Disk size in GB
157
self.Placement: Placement = None # Placement configuration
158
self.DiskName: str = None # Disk name
159
self.DiskCount: int = None # Number of disks
160
self.DiskChargeType: str = None # Billing method
161
self.Shareable: bool = None # Multi-instance attachment support
162
163
class AttachDisksRequest(AbstractModel):
164
def __init__(self):
165
"""Request to attach disks to instances."""
166
self.DiskIds: list = None # Disk IDs to attach
167
self.InstanceId: str = None # Target instance ID
168
self.DeleteWithInstance: bool = None # Delete disk when instance terminates
169
```
170
171
### Response Models
172
173
Structured output objects from API calls containing results, metadata, and error information. All response models follow the naming pattern `{Action}Response`.
174
175
#### Common Response Structure
176
177
```python { .api }
178
class CommonResponse(AbstractModel):
179
def __init__(self):
180
"""Common response structure across all APIs."""
181
self.RequestId: str = None # Unique request identifier
182
self.Error: Error = None # Error information if call failed
183
184
class Error(AbstractModel):
185
def __init__(self):
186
"""Error information structure."""
187
self.Code: str = None # Error code
188
self.Message: str = None # Error message
189
```
190
191
#### CVM Response Models
192
193
```python { .api }
194
class RunInstancesResponse(AbstractModel):
195
def __init__(self):
196
"""Response from instance creation."""
197
self.InstanceIdSet: list = None # Created instance IDs
198
self.RequestId: str = None # Request identifier
199
200
class DescribeInstancesResponse(AbstractModel):
201
def __init__(self):
202
"""Response from instance query."""
203
self.TotalCount: int = None # Total matching instances
204
self.InstanceSet: list = None # List of Instance objects
205
self.RequestId: str = None # Request identifier
206
207
class TerminateInstancesResponse(AbstractModel):
208
def __init__(self):
209
"""Response from instance termination."""
210
self.RequestId: str = None # Request identifier
211
```
212
213
#### CBS Response Models
214
215
```python { .api }
216
class CreateDisksResponse(AbstractModel):
217
def __init__(self):
218
"""Response from disk creation."""
219
self.DiskIdSet: list = None # Created disk IDs
220
self.RequestId: str = None # Request identifier
221
222
class DescribeDisksResponse(AbstractModel):
223
def __init__(self):
224
"""Response from disk query."""
225
self.TotalCount: int = None # Total matching disks
226
self.DiskSet: list = None # List of Disk objects
227
self.RequestId: str = None # Request identifier
228
```
229
230
### Data Models
231
232
Complex structured objects representing cloud resources, configurations, and metadata. These models are used within request and response objects.
233
234
#### Instance Models
235
236
```python { .api }
237
class Instance(AbstractModel):
238
def __init__(self):
239
"""CVM instance information."""
240
self.InstanceId: str = None # Instance identifier
241
self.InstanceName: str = None # Instance name
242
self.InstanceType: str = None # Instance specification
243
self.InstanceState: str = None # Current state
244
self.ImageId: str = None # System image ID
245
self.Placement: Placement = None # Placement information
246
self.PrivateIpAddresses: list = None # Private IP addresses
247
self.PublicIpAddresses: list = None # Public IP addresses
248
self.SystemDisk: SystemDisk = None # System disk information
249
self.DataDisks: list = None # Data disk information
250
self.VirtualPrivateCloud: VirtualPrivateCloud = None # VPC info
251
self.SecurityGroupIds: list = None # Security group IDs
252
self.Tags: list = None # Resource tags
253
self.CreatedTime: str = None # Creation timestamp
254
self.ExpiredTime: str = None # Expiration timestamp
255
```
256
257
#### Storage Models
258
259
```python { .api }
260
class Disk(AbstractModel):
261
def __init__(self):
262
"""Cloud block storage disk information."""
263
self.DiskId: str = None # Disk identifier
264
self.DiskName: str = None # Disk name
265
self.DiskType: str = None # Disk type
266
self.DiskSize: int = None # Disk size in GB
267
self.DiskState: str = None # Current state
268
self.Attached: bool = None # Attachment status
269
self.InstanceId: str = None # Attached instance ID
270
self.Placement: Placement = None # Placement information
271
self.CreatedTime: str = None # Creation timestamp
272
self.DiskChargeType: str = None # Billing method
273
274
class SystemDisk(AbstractModel):
275
def __init__(self):
276
"""System disk configuration."""
277
self.DiskType: str = None # Disk type
278
self.DiskSize: int = None # Disk size in GB
279
self.DiskId: str = None # Disk identifier
280
281
class DataDisk(AbstractModel):
282
def __init__(self):
283
"""Data disk configuration."""
284
self.DiskType: str = None # Disk type
285
self.DiskSize: int = None # Disk size in GB
286
self.DeleteWithInstance: bool = None # Delete with instance
287
self.SnapshotId: str = None # Source snapshot ID
288
```
289
290
#### Network Models
291
292
```python { .api }
293
class VirtualPrivateCloud(AbstractModel):
294
def __init__(self):
295
"""VPC configuration."""
296
self.VpcId: str = None # VPC identifier
297
self.SubnetId: str = None # Subnet identifier
298
self.AsVpcGateway: bool = None # VPC gateway role
299
self.PrivateIpAddresses: list = None # Private IP addresses
300
301
class InternetAccessible(AbstractModel):
302
def __init__(self):
303
"""Internet access configuration."""
304
self.InternetChargeType: str = None # Billing method
305
self.InternetMaxBandwidthOut: int = None # Outbound bandwidth limit
306
self.PublicIpAssigned: bool = None # Assign public IP
307
self.BandwidthPackageId: str = None # Bandwidth package ID
308
```
309
310
#### Authentication Models
311
312
```python { .api }
313
class LoginSettings(AbstractModel):
314
def __init__(self):
315
"""Instance login configuration."""
316
self.Password: str = None # Login password
317
self.KeyIds: list = None # SSH key pair IDs
318
self.KeepImageLogin: bool = None # Keep image login settings
319
```
320
321
### Advanced Model Usage
322
323
**Complex Request Construction:**
324
325
```python
326
from tencentcloud.cvm.v20170312 import models
327
328
# Build complex instance launch request
329
request = models.RunInstancesRequest()
330
331
# Basic configuration
332
request.ImageId = "img-9qabwvbn" # Ubuntu 20.04
333
request.InstanceType = "S5.LARGE8" # 4 vCPU, 8GB RAM
334
request.InstanceCount = 2
335
336
# Placement configuration
337
placement = models.Placement()
338
placement.Zone = "ap-shanghai-1"
339
placement.ProjectId = 0
340
request.Placement = placement
341
342
# VPC configuration
343
vpc = models.VirtualPrivateCloud()
344
vpc.VpcId = "vpc-12345678"
345
vpc.SubnetId = "subnet-87654321"
346
vpc.PrivateIpAddresses = ["10.0.1.10", "10.0.1.11"]
347
request.VirtualPrivateCloud = vpc
348
349
# System disk configuration
350
system_disk = models.SystemDisk()
351
system_disk.DiskType = "CLOUD_PREMIUM"
352
system_disk.DiskSize = 50
353
request.SystemDisk = system_disk
354
355
# Data disk configuration
356
data_disk = models.DataDisk()
357
data_disk.DiskType = "CLOUD_SSD"
358
data_disk.DiskSize = 200
359
data_disk.DeleteWithInstance = True
360
request.DataDisks = [data_disk]
361
362
# Internet access configuration
363
internet = models.InternetAccessible()
364
internet.InternetChargeType = "TRAFFIC_POSTPAID_BY_HOUR"
365
internet.InternetMaxBandwidthOut = 100
366
internet.PublicIpAssigned = True
367
request.InternetAccessible = internet
368
369
# Login configuration
370
login = models.LoginSettings()
371
login.KeyIds = ["skey-12345678"]
372
request.LoginSettings = login
373
374
# Tag configuration
375
tag_spec = models.TagSpecification()
376
tag_spec.ResourceType = "instance"
377
tag_spec.Tags = [
378
models.Tag(Key="Environment", Value="Production"),
379
models.Tag(Key="Application", Value="WebServer")
380
]
381
request.TagSpecification = [tag_spec]
382
383
# Execute request
384
response = client.RunInstances(request)
385
print(f"Created instances: {response.InstanceIdSet}")
386
```
387
388
**Response Processing:**
389
390
```python
391
# Query instances and process response
392
desc_request = models.DescribeInstancesRequest()
393
desc_response = client.DescribeInstances(desc_request)
394
395
print(f"Total instances: {desc_response.TotalCount}")
396
397
for instance in desc_response.InstanceSet:
398
print(f"Instance {instance.InstanceId}:")
399
print(f" Name: {instance.InstanceName}")
400
print(f" Type: {instance.InstanceType}")
401
print(f" State: {instance.InstanceState}")
402
print(f" Private IPs: {instance.PrivateIpAddresses}")
403
print(f" Public IPs: {instance.PublicIpAddresses}")
404
print(f" Created: {instance.CreatedTime}")
405
406
# Process tags
407
if instance.Tags:
408
print(" Tags:")
409
for tag in instance.Tags:
410
print(f" {tag.Key}: {tag.Value}")
411
412
# Process disks
413
if instance.DataDisks:
414
print(" Data Disks:")
415
for disk in instance.DataDisks:
416
print(f" {disk.DiskType}: {disk.DiskSize}GB")
417
```
418
419
**Model Serialization and Storage:**
420
421
```python
422
import json
423
424
# Serialize model to JSON for storage/transmission
425
instance_data = desc_response.to_json_string(indent=2)
426
427
# Store in file
428
with open("instances.json", "w") as f:
429
f.write(instance_data)
430
431
# Load from file
432
with open("instances.json", "r") as f:
433
json_data = f.read()
434
435
# Recreate model from JSON
436
new_response = models.DescribeInstancesResponse()
437
new_response.from_json_string(json_data)
438
439
# Use reconstructed data
440
print(f"Loaded {new_response.TotalCount} instances from file")
441
```
442
443
**Filter Construction:**
444
445
```python
446
# Build complex filters for instance queries
447
request = models.DescribeInstancesRequest()
448
449
# Filter by zone
450
zone_filter = models.Filter()
451
zone_filter.Name = "zone"
452
zone_filter.Values = ["ap-shanghai-1", "ap-shanghai-2"]
453
454
# Filter by instance state
455
state_filter = models.Filter()
456
state_filter.Name = "instance-state-name"
457
state_filter.Values = ["running", "stopped"]
458
459
# Filter by tag
460
tag_filter = models.Filter()
461
tag_filter.Name = "tag:Environment"
462
tag_filter.Values = ["Production"]
463
464
# Combine filters
465
request.Filters = [zone_filter, state_filter, tag_filter]
466
request.Limit = 50
467
468
response = client.DescribeInstances(request)
469
print(f"Found {len(response.InstanceSet)} filtered instances")
470
```