本文介绍了如何使用请求模块使用 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!