Python requests.post,不能使用文件作为"data"变量


headers = {
"User-Agent": "Mozilla/5.0",
'accept': 'application/json',
'Content-Type': 'application/json',
}
with open("jsonattempt.txt","r") as f:
data = f.read()
json_data = "'" + data + "'"
response = requests.post('https://www.pathofexile.com/api/trade/search/Standard', headers=headers, data=json_data)
print(response)

一般来说,有一个卷曲请求如下:

curl -X 'POST' 
'https://www.pathofexile.com/api/trade/search/Standard' 
-H 'accept: application/json' 
-H 'Content-Type: application/json' 
-d '{
"query": {
"status": {
"option": "online"
},
"type": "Turquoise Amulet",
"stats": [
{
"type": "and",
"filters": [
{
"id": "pseudo.pseudo_total_mana",
"value": {
"min": 47,
"max": 49
},
"disabled": false
}
]
}
]
},
"sort": {
"price": "asc"
}
}'

它返回了一堆不必要的东西。

我的json_data变量和jsonatant.txt与-d参数相同,我在开始和结束处添加了":

{
"query": {
"status": {
"option": "online"
},
"type": "Turquoise Amulet",
"stats": [
{
"type": "and",
"filters": [
{
"id": "pseudo.pseudo_total_mana",
"value": {
"min": 47,
"max": 49
},
"disabled": false
}
]
}
]
},
"sort": {
"price": "asc"
}
}

我将curl请求转换为python,这是顶部的代码,我将数据添加为json_data,并对post请求进行yeet处理,但一直得到400 Bad request。

请求401是未授权的AFAIK,所以我不需要OAuth2密钥。如何根据请求适当地插入json文件?

(完全相同的json在https://app.swaggerhub.com/apis-docs/Chuanhsing/poe/1.0.0#/Trade/get_api_trade_fetch__items_上工作,我只是问如何将json文件正确插入requests.post。(

为什么要在JSON内容周围添加引号?这没有任何意义。这些报价不属于curl请求的一部分。如果你只是写。。。

import requests
headers = {
"User-Agent": "Mozilla/5.0",
"accept": "application/json",
"Content-Type": "application/json",
}
with open("jsonattempt.txt", "r") as f:
data = f.read()
response = requests.post(
"https://www.pathofexile.com/api/trade/search/Standard",
headers=headers,
data=data,
)
print(response)

它按预期工作。

事实上,你可以进一步简化它;你不需要自己读取文件数据,你可以让requests来做:

import requests
headers = {
"User-Agent": "Mozilla/5.0",
"accept": "application/json",
"Content-Type": "application/json",
}
with open("jsonattempt.txt", "r") as f:
response = requests.post(
"https://www.pathofexile.com/api/trade/search/Standard",
headers=headers,
data=f,
)
print(response)
import json
#  some codes here
with open("jsonattempt.txt","r") as f:
data = f.read()
json_data = json.loads(data)
#  rest of codes here

您的请求需要json类型的数据,而您正在传递一个字符串。json.loads方法将字符串转换为json。试试看。

最新更新