Python的请求模块,Json和APIs

2024-04-25 00:26:59 发布

您现在位置:Python中文网/ 问答频道 /正文

  1. 我需要识别API中“account\u type”的任何帐户 从API中被列为“未知”而不是“链接”。你知道吗
  2. 然后,我需要将标识为“未知”“帐户类型”的“所有者id”字段与csv中列出的所有者id进行比较。你知道吗
  3. 然后我需要将匹配帐户csv中的字段发布到另一个API。你知道吗

我在计算如何生成与“未知”“帐户类型”匹配的所有者id列表时遇到问题,然后将它们与csv中与所有者id匹配的帐户进行比较。任何帮助都将不胜感激。我在下面列出了我所取得的进展,以及api中一个帐户的简短片段。谢谢!你知道吗

# This is what I started with:
import requests  
import json   

r = requests.get ("https://chapi.cloudhealthtech.com/v1/aws_accounts?api_key=xxxxxxxxxxxxxxxx")   
data = r.json()

响应数据:

{
  "aws_accounts": [  
    {  
      "id": XXXXXXXXXXXX,  
      "name": "XXXXXXXXXXXX",  
      "amazon_name": "XXXXXXXX",  
      "owner_id": "XXXXXXXXXX",  
      "hide_public_fields": false,  
      "region": "global",  
      "created_at": "2018-05-09T10:31:19Z",  
      "updated_at": "2018-10-24T22:02:49Z",  
      "account_type": "Linked",  
      "vpc_only": true,  
      "cluster_name": "XXX",  
      "status": {  
        "level": "yellow",  
        "last_update": "2018-12-09T13:25:01Z"  
      },  
      "authentication": {  
        "protocol": "assume_role",  
        "assume_role_arn": "arn:aws:iam::XXXXXXXXXXXXX:role/CloudHealthXAccountReaderRole",  
        "assume_role_external_id": "XXXXXXXXXXXXXXXXXXXXX"  
      },  
      "billing": {  
        "is_consolidated": false  
      },  
      "cloudtrail": {  
        "enabled": false
      }
    }
  ]
}

Tags: csvnameimportawsapiidfalse类型
1条回答
网友
1楼 · 发布于 2024-04-25 00:26:59

例如,如果您的csv文件如下所示:

id,sample_data
1,sample
2,sample
3,sample
4,sample
5,sample

请尝试以下代码:

import requests
import csv  

r = requests.get("https://chapi.cloudhealthtech.com/v1/aws_accounts", params={"api_key": "xxxxxxxxxxxxxxxx"})   
data = r.json()

# we read csv file and create list with ids that we should post
with open('ids.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    # skip column names row
    next(csv_reader, None)
    ids = [row[0] for row in csv_reader]

# we parse through our aws_accounts to get Unknown types and which ids in our list
accounts_to_post = []
for account in data["aws_accounts"]:
    if account["account_type"] == "Unknown" and account["id"] in ids:
        accounts_to_post.append(account)

# at last, we post those accounts to your api
r = requests.post('your_api_url', data = {'accounts':accounts_to_post})

由于你的问题细节有点模糊,可能会很复杂。我也不知道你的帐户应该如何输出到api,所以我带来了最简单的解决方案。你知道吗

相关问题 更多 >