如何使用API和Python提取数据



我有一个服务器银行,我使用API提取有关存储的数据。要获得存储uuid(json中的命名存储(的详细信息,我使用以下代码:

srvdet = requests.get('https://hhh.com/1.2/server/76856585', auth=HTTPBasicAuth('login', 'pass'))
srvdet_json = srvdet.json()
datas = srvdet.json()
print(datas)

结果为json:

{
"server": {
"boot_order": "",
"core_number": "2",
"created": ,
"firewall": "off",
"host": ,
"hostname": "hello",
"ip_addresses": {
"ip_address": [
{
"access": "private",
"address": "",
"family": ""
},
{
"access": "",
"address": "",
"family": "",
"part_of_plan": ""
}
]
},
"license": 0,
"memory_amount": "",
"nic_model": "",
"plan": "",
"plan_ipv4_bytes": "",
"plan_ipv6_bytes": "0",
"state": "started",
"storage_devices": {
"storage_device": [
{
"address": "",
"boot_disk": "0",
"part_of_plan": "",
"storage": "09845",
"storage_size": ,
"storage_title": "",
"type": ""

}

目前,它运行得非常好。问题是当我需要得到"09845">,这是存储的值。当我尝试使用此代码时:

for storage in datas['server']['storage_devices']['storage_device']:
srvstorage = storage
print(srvstorage)

结果是:

{'storage': '09845', 'storage_size':, 'address': '', 'boot_disk': '0', 'type': '', 'part_of_plan': 'yes', 'storage_title': ''}

我做错了什么?如何保存";09845";变量中?

编辑:

现在,我在尝试访问有关存储的详细信息时出错。我想提取json:中状态的备份状态

{
"storage": {
"access": "private",
"backup_rule": {},
"backups": {
"backup": []
},
"license": 0,
"part_of_plan": "",
"servers": {
"server": [
""
]
},
"size": ,
"state": "online",
"tier": "",
"title": "",
"type": "",
"uuid": "",
"zone": ""
}
}

当我执行这个代码时:

bkpdet = requests.get('https://fffff.com/1.2/storage/08475', auth=HTTPBasicAuth('login', 'pass'))
bkpdet_json = bkpdet.json()
datastg = bkpdet.json()
print(datastg)
for sts in datastg['storage']:
bkpsts = sts['state']
print(bkpsts)

我得到这个错误:

Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: string indices must be integers

整个想法是在最后使用以下代码获得有关状态的信息:

if bkpsts == "online":
print('Backup has been created.')
else bkpsts == "backuping":
print('Backup creation is in progress.')
else:
print(bkpdet.status_code)

我一直在找,但仍然找不到这里出了什么问题。

当你想访问存储时,你错过了一个键,你循环访问它,它就可以了。但在每次迭代中,您都会得到一个字典,需要从中调用正确的键,在您的例子中是storage

for storage in datas['server']['storage_devices']['storage_device']: 
srvstorage = storage.get("storage", None) 
print(srvstorage)

备注

最好使用get方法,因为您可能会遇到内部存储信息不足的设备,通过使用get可以避免使用KeyError

您只需执行

for device in datas['server']['storage_devices']['storage_device']:
device_storage = device['storage']
print(device_storage)

最新更新