使用 POST 的 'requests' 模块,我想从整个 csv cells/values 中获取整个 JSON 正文

Using 'requests' module for POST, I want to pick up entire JSON body from whole csv cells/values

我一直在尝试编写一些 python 脚本来自动执行一些 API 测试。

我需要它从 CSV 或其他格式文件中提取整个 JSON 正文,而不是每个文件只有一个正文,而是遍历其中的所有“正文”。

我编造的方式是,每个单元格或值都是一个整体。这来自于我在 Google 表格中管理各种测试的方式,整个 JSON 主体在它们自己的单元格中,然后可以轻松导出为 CSV 文件。

问题是我不断遇到“格式错误”类型的错误。我认为问题在于,当它把它作为 CSV“值”拾取时,它输入的数据很奇怪,这就是它不起作用的原因。

示例“有问题的”输入,即通过断点捕获的从 CSV 文件中获取的值:

'{"post":2027,"name":"Test User","email":"email@mail.com","body":"lorem ipsum4"}'

我已经尝试了很多东西。这就是我现在所在的位置。下面是一些示例数据和更多解释。

代码:

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")

示例数据。在这里,每一行都是 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"}

示例输出:(“文本响应”稍微 post- 格式化以便于阅读)

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

我注意到的“奇怪”之处在于,有时(在以前的版本中)我可以将打印出的正文(例如在示例输出中)输入回 JSON,当我正在使用断点,这将完美地工作。所以我尝试使用一些东西来“捕捉”那个“正在工作的印刷体”,但这并不是真的可行,或者我没有做对。

csv.reader returns rows of strings, so the strings each need to be converted to a Python object for the json keyword argument in requests.request. We can use json.loads 反序列化字符串。

req_obj = json.loads(col)
r = requests.request("POST", url, headers = headers, json = req_obj)