0

我使用下面的代码成功地将消息发送到 pushover,但是我想发送最新 API 中介绍的图片附件。我如何能够将最后一个代码示例转换为在 python 中工作。

工作代码:

import httplib, urllib
conn = httplib.HTTPSConnection("api.pushover.net:443")
conn.request("POST", "/1/messages.json",
  urllib.urlencode({
    "token": "APP_TOKEN",
    "user": "USER_KEY",
    "message": "hello world",
  }), { "Content-type": "application/x-www-form-urlencoded" })
conn.getresponse()

示例 API

curl -s \
 --form-string "token=APP_TOKEN" \
 --form-string "user=USER_KEY" \
 --form-string "message=here is an image attachment" \
 -F "attachment=@/path/to/your/image.jpg" \
 https://api.pushover.net/1/messages.json
4

1 回答 1

1

我没有尝试过 urllib,但请求成功。我真的不知道你是否想使用那个模块。但无论如何,这里是代码。

import requests

r = requests.post("https://api.pushover.net/1/messages.json", data={"token":"APP_TOKEN","user":"USER_KEY","message":"Got Image?"}, files={"attachment":open("PATH_TO_IMAGE","rb")})

把它分解。您传递请求的参数以在 dict data中进行编码。然后你在 dict files中传递文件。重要的是文件是用 rb 打开的(读取二进制文件)。

于 2018-01-26T13:25:30.570 回答