khv*_*hvc 5 python csv json automated-tests google-sheets
我一直在尝试编写一些Python脚本来自动化一些API测试。
我需要它从 CSV 或其他格式文件中获取整个 JSON 主体,但不仅仅是每个文件一个主体,而是迭代其中的所有“主体”。
我的说法是,每个细胞或值都是一个整体。这来自我在 Google Sheets 中管理各种测试的方式,将整个 JSON 主体放在自己的单元格中,然后可以轻松导出为 CSV 文件。
问题是我不断遇到“格式错误”类型错误。我认为问题在于,当它把它作为 CSV“值”时,它会奇怪地输入数据,这就是它不起作用的原因。
“有问题的”输入示例,即从 CSV 文件中获取的值(通过断点捕获):
'{"post":2027,"name":"Test User","email":"email@mail.com","body":"lorem ipsum4"}'
Run Code Online (Sandbox Code Playgroud)
我已经尝试了很多事情。这就是我现在所处的位置。下面是一些示例数据和更多解释。
代码:
from os import read
import requests
import csv
import json
filename = 'file.csv'
url = "https://gorest.co.in/public/v1/posts/[id]/comments"
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer tricked ya"
}
with open(filename) as cF:
reader = csv.reader(cF)
for idx,row in enumerate(reader):
for col in row:
print("Body: ", col)
r = requests.request("POST", url, headers = headers, json = col)
print("Status: ", r.status_code)
print("Status: ", r.reason)
print("Text response: ", r.text)
print("\nTest number: ",idx,"\n")
Run Code Online (Sandbox Code Playgroud)
样本数据。在这里,每一行都是 csv 文件中的一行:
{"post":2027,"name":"Test User","email":"email@mail.com","body":"lorem ipsum1"}
{"post":2027,"name":"Test User","email":"email@mail.com","body":"lorem ipsum2"}
{"post":2027,"name":"Test User","email":"email@mail.com","body":"lorem ipsum3"}
{"post":2027,"name":"Test User","email":"email@mail.com","body":"lorem ipsum4"}
Run Code Online (Sandbox Code Playgroud)
示例输出:(“文本响应”稍微经过后期格式化以提高可读性)
Body: {"post":2027,"name":"Test User","email":"email@mail.com","body":"lorem ipsum4"}
Status: 422
Status: Unprocessable Entity
Text response:
{
"meta": null,
"data": [{
"field": "name",
"message": "can't be blank"
}, {
"field": "email",
"message": "can't be blank"
}, {
"field": "body",
"message": "can't be blank"
}]
}
Test number: 4
Run Code Online (Sandbox Code Playgroud)
我注意到的“奇怪”的事情是,当我使用断点时,有时(在以前的版本中)我可以将打印出来的正文(例如在示例输出中)输入回 JSON,这将工作完美。所以我尝试使用一些东西来“捕获”“工作印刷体”,但这并不是真正可行,或者我做得不对。
csv.reader返回字符串行,因此每个字符串都需要转换为requests.requestjson中关键字参数的 Python 对象。我们可以使用json.loads来反序列化字符串。
req_obj = json.loads(col)
r = requests.request("POST", url, headers = headers, json = req_obj)
Run Code Online (Sandbox Code Playgroud)