Python POST请求带有JSON数据的工作在Requestbin上,但在本地不起作用。

huangapple go评论71阅读模式
英文:

Python POST requests to an API with JSON data work on Requestbin, but not locally

问题

以下是翻译好的内容:

我正在使用Python的Requests库向服务器进行API调用。在本地,我有一个目录中的JSON数据,所有文件的扩展名都是.json。我像这样将JSON文件导入到我的Python文件中:

with open("./json_payloads/data.json") as user_file:
    json_data = user_file.read()

json_data 的类型是字符串,并且是JSON格式的。当我尝试进行API的POST请求时,服务器返回一个500错误。

在Requestbin中执行相同的操作时,我一切都做得一模一样,只是不是从文件中提取JSON,而是从Requestbin的数据存储中提取。我像这样提取它:

data_store = pd.inputs["data_store"]
json_data = data_store["json_data"]

而且我从服务器获得了一个200的结果。

关于为什么在本地无法正常工作,是否有任何见解?我更希望在本地完成这个过程,以便在后续步骤中上传文件。

英文:

I'm making API calls to a server with Python's Requests library. Locally, I have the JSON data in a directory, all files ending with .json. I am importing a JSON file to my Python file like so:

with open("./json_payloads/data.json") as user_file:
    json_data = user_file.read()

The type json_data is String and in JSON format. When I try the API POST request, I get back a 500 error from the server.

When doing it from Requestbin, I do everything exactly the same except instead of pulling JSON from a file, I have it in Requestbin's data store. I pull it like so:

  data_store = pd.inputs["data_store"]
  json_data = data_store["json_data"]

And I get back a 200 result from the server.

Any insights on why this is not working locally? I would much rather complete this locally for later steps in the process, like when I will upload files.

答案1

得分: 1

json_data 从文件中读取的是 str 类型。在发送请求之前,使用 json.loads 将其转换为 dict 类型。

import json
json_data = json.loads(json_data)
英文:

json_data read from the file is of type str. Convert it to a dict using json.loads before sending it with a request.

import json
json_data = json.loads(json_data)

huangapple
  • 本文由 发表于 2023年3月7日 10:45:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75657616.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定