尝试使用 Python 通过 API 访问数据时出错 [英] Error when trying to access data via API using Python

查看:39
本文介绍了尝试使用 Python 通过 API 访问数据时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用 API 访问有关服务器存储的详细信息时出错.我想提取 json 中 state 的备份状态:

I get error when trying to access details about servers storage using API. I want to extract backup status which is state in 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

如何访问状态*?整个想法是最后使用此代码获取有关状态的信息:

How can I access state*? The whole idea is to at the end get info about status using this code:

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

我正在搜索,但仍然找不到这里有什么问题.

I was searching but still cannot find what is wrong here.

推荐答案

使用时:

for sts in datastg['storage']:

sts 将是一个字符串键.你试图把它当作一本字典.

sts will be a string key. You are trying to treat it like an dictionary.

如果只需要state值,可以直接访问:

If you just need the state value, you can access it directly:

datastg['storage']['state']

如果要遍历storage下的所有键值对,可以使用items()来同时对key和value进行迭代.

If you want to iterate all key value pairs under storage, you can use items() to both key and value.

for key, value in datastg['storage'].items():
    print(key,":", value)

这篇关于尝试使用 Python 通过 API 访问数据时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆