POST:是否需要序列化JSON数据

问题描述 投票:0回答:1

我的Rest API在发布JSON数据时效果很好。我在服务器上使用它:

req = request.get_json()
dicti = json.loads(req)
#It(dicti) is then processed.

在客户端上,我这样进行(使用python请求):

dat = {'a':1, 'b':2}
serialised_dat = json.dumps(dat)
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
requests.post("myurl", json = serialised_dat, headers = headers)

而且,一切正常。但是,当我从失眠之类的其他客户端测试我的Rest API时,我收到内部服务器错误,这很公平,因为粘贴到其中的json未序列化。我需要序列化json,然后将其粘贴到其他客户端以获得成功吗?要么我上面用来将json发送到flask的方法本身是否错误?

python json flask-restful
1个回答
0
投票

json参数的值应该是一个将为您序列化的对象。

requests.post("myurl", json=dat, headers=headers)

如果您有预序列化的数据,请改用data关键字参数。

requests.post("myurl", data=json.dumps(dat), headers=headers)
© www.soinside.com 2019 - 2024. All rights reserved.