Python 从文本/CSV 文件解析为 request.post API



我想把下面的curl命令变成python脚本。因为我需要从文本或csv加载数据信息。但是我很难从文件中解析数据。有人可以帮助我理解这一点。谢谢。

curl -X POST -d '{"hostname":"localhost.localdomain","version":"v2c","community":"public"}' -H 'X-Auth-Token: my_api_token' https://xxx/api/v0/devices

我的代码:

import requests
import json
import csv
auth_token = "my_api_token"
api_url_base = 'http://xxxx/api/v0/devices'
headers = {'Content-Type': 'application/json',
'Authorization': 'Bearer {0}'.format(auth_token)}

def add_device(name, filename): 
with open(nodes.csv, 'r') as f:
add_device = f.readline()
add_device = {'hostname': $name, 'version': %version, 'community': %community}
response = requests.post(api_url_base, headers=headers, json=add_device)
print(response.json())

您应该拆分 CSV 内容。COUNT 在 CSV 文件中显示逗号分隔项目的计数。

add_devices = []
with open(nodes.csv, 'r') as f:
line = f.readline():
items = line.split(',', COUNT)  # if COUNT is 3 then
add_devices = {'hostname': items[0], 'version': items[1], 'community': items[2]}

最新更新