【问题标题】:How to post a json file with requests如何发布带有请求的 json 文件
【发布时间】:2019-01-18 06:59:04
【问题描述】:

编辑:抱歉,这一天很长。我以为我在描述中添加了更多信息。这是我的代码:

import requests
import json

url = 'https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone?version=2017-09-21'
headers = {'Authorization' : ('username', 'password'), 'Accept' : 'application/json', 'Content-Type' : 'application/json'}
r = requests.post(url, data=open('tweets.json', 'rb'), headers=headers)

这是我收到的错误,我在正确的目录中,并且 100% 有一个名为 tweets.json 的文件。

FileNotFoundError: [Errno 2] No such file or directory: 'tweets.json'

我正在尝试使用 Python 包的 Requests 向 IBM Watson 写入 API 请求。我已经尝试了几个小时,但没有运气。

我已经成功地在 cURL 中为 api 写了一个 POST,但我真的很难将它导入我的应用程序所在的语言 python。

谁能帮我把这个 cURL 请求翻译成 Python 请求?

curl -X POST -u "password:username" --header "Content-Type: application/json" --data-binary @tone.json "https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone?version=2017-09-21"

最好, 瑞恩

【问题讨论】:

标签: python-3.x curl python-requests


【解决方案1】:

试试这样 - 你需要抓取并加载你的 json 数据,你还需要做你的身份验证略有不同:

import requests
import json
from requests.auth import HTTPBasicAuth

url = 'https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone?version=2017-09-21'
headers = {'Accept' : 'application/json', 'Content-Type' : 'application/json'}

with open('tweets.json') as f:
    data = json.loads(f.read())

r = requests.post(url, data=data, headers=headers, auth=HTTPBasicAuth('username', 'password'))

如果您的 JSON 文件非常大,您可以像在问题中那样传递数据,但这在 IMO 中更具可读性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-21
    • 2015-10-08
    • 2017-08-14
    • 2023-03-08
    • 1970-01-01
    • 2020-01-07
    • 2016-11-05
    • 1970-01-01
    相关资源
    最近更新 更多