Python requests 库发送 body 只有一个 list 的请求的写法

2020-12-01 11:59:05 +08:00
 kickcandy

[300004167],发送的 body 是这样的格式,对,没有 key,只有 value,查过确实也是正确的 json 格式,用 postman 发送可以正常返回,但是用 python 的 requests 库,试了好几种写法都是报错:

各位朋友有没有好的办法解决,谢谢!

----self.DeviceManage.send_post(url, json.dumps([300004167]), header)

报错:json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

----self.DeviceManage.send_post(url, [str(300004167)], header)

报错:ValueError: too many values to unpack (expected 2)

----self.DeviceManage.send_post(url, numpy.array([300004167]), header) #试图转数组

报错:json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

1614 次点击
所在节点    问与答
13 条回复
Pagliacii
2020-12-01 12:07:07 +08:00
用 `json.dumps` 一下,如这样:![image.png]( https://i.loli.net/2020/12/01/WPFOI7G9UV3x1Ku.png)
Pagliacii
2020-12-01 12:08:10 +08:00
@Pagliacii #1 至于你用了 `json.dumps` 报错,就要看看 `send_post` 是怎么写的了
leavic
2020-12-01 12:16:33 +08:00
wireshark 抓包看看发出去的有什么区别不就知道了。
kickcandy
2020-12-01 13:11:04 +08:00
@Pagliacii
send_post 方法就是调了 requests.post 方法,做了一些处理封装:

def send_post(self, url, data, header):
result = requests.post(url=url, data=data, headers=header)
# res = result1.json()
result_str = json.dumps(result.json(), ensure_ascii=False, sort_keys=True, indent=2) # 结果转字符串
result_dict = json.loads(result_str) # 结果转字典
return result, result_dict
zhijiansha
2020-12-01 13:17:36 +08:00
把 data 改成 json=[123]试试?
binux
2020-12-01 13:20:12 +08:00
第一个报错是 result_dict = json.loads(result_str) 和你 post 无关
Pagliacii
2020-12-01 13:22:23 +08:00
@kickcandy #4 那你就加上一些日志或者 `print` 语句,确定一下具体是哪里出错了。比如:

```
result = requests.post(url=url, data=data, headers=header)
print(f"{result.content}")
result_str = json.dumps(result.json(), ensure_ascii=False, sort_keys=True, indent=2)
print(f"{result_str=}")
result_dict = json.loads(result_str)
print(f"{result_dict=}")
```
cryingsky
2020-12-01 13:22:41 +08:00
请求返回结果解析有问题
返回数据应该不是 json
iyaozhen
2020-12-01 13:25:27 +08:00
这就是 send_post 瞎封装

不改 send_post 源码的话,self.DeviceManage.send_post(url, json.dumps([300004167]), header)
header 里面加上 content type json
kickcandy
2020-12-01 14:14:04 +08:00
@iyaozhen 是,发现了是封装的问题,返回的不是 json 格式的
kickcandy
2020-12-01 14:22:08 +08:00
@cryingsky 返回结果不是 json,意味着这个接口不规范?
cryingsky
2020-12-01 14:36:02 +08:00
@kickcandy #11 那就看你接口规规范怎么定的
bnm965321
2020-12-01 14:37:39 +08:00
单 list 的 JSON 有安全问题,之前在 tornado 的文档看到过

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/730905

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX