如何使用请求模块使用Python将JSON文件的内容发布到RESTFUL API [英] how to POST contents of JSON file to RESTFUL API with Python using requests module
本文介绍了如何使用请求模块使用Python将JSON文件的内容发布到RESTFUL API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好的,我放弃.我正在尝试发布包含JSON的文件的内容.该文件的内容如下所示:
Okay, I give up. I am trying to post the contents of a file that contains JSON. The contents of the file look like this:
{
"id":99999999,
"orders":[
{
"ID":8383838383,
"amount":0,
"slotID":36972026
},
{
"ID":2929292929,
"amount":0,
"slotID":36972026
},
{
"ID":4747474747,
"amount":0,
"slotID":36972026
}]
}
以下是可能与代码不符的代码:
Here's the code which is probably way off the mark:
#!/usr/bin/env python3
import requests
import json
files = {'file': open(‘example.json’, 'rb')}
headers = {'Authorization' : ‘(some auth code)’, 'Accept' : 'application/json', 'Content-Type' : 'application/json'}
r = requests.post('https://api.example.com/api/dir/v1/accounts/9999999/orders', files=files, headers=headers)
推荐答案
这应该有效,但是它适用于非常大的文件.
This should work, but it's meant for very large files.
import requests
url = 'https://api.example.com/api/dir/v1/accounts/9999999/orders'
headers = {'Authorization' : ‘(some auth code)’, 'Accept' : 'application/json', 'Content-Type' : 'application/json'}
r = requests.post(url, data=open('example.json', 'rb'), headers=headers)
如果要发送较小的文件,请以字符串形式发送.
If you want to send a smaller file, send it as a string.
contents = open('example.json', 'rb').read()
r = requests.post(url, data=contents, headers=headers)
这篇关于如何使用请求模块使用Python将JSON文件的内容发布到RESTFUL API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文