【问题标题】:Python: curl -F equivalent with Requests or otherPython:curl -F 等价于 Requests 或其他
【发布时间】:2016-09-19 00:11:09
【问题描述】:

我想重现以下 curl -F 请求 (from the Messenger API) 将图像文件和参数发送到 Messenger 的发送 API:

curl  \
-F recipient='{"id":"USER_ID"}' \
-F message='{"attachment":{"type":"image", "payload":{}}}' \
-F filedata=@/tmp/shirt.png \
"https://graph.facebook.com/v2.6/me/messages?access_token=PAGE_ACCESS_TOKEN"

我正在使用请求,我尝试了很多很多东西(包括使用正确的收件人 ID 等。例如:

recipient = '{"id":"USER_ID"}'
message = '{"attachment":{"type":"image", "payload":{}}}'
files = [("recipient", recipient), ("message", message), ("filedata", open(imagePath, 'rb'))]
r = requests.post('https://graph.facebook.com/v2.6/me/messages?access_token=ACCESS_TOKEN', files=files)

我也试过了:

files = {"recipient" : recipient, "message" : message, "filedata" : open(imagePath, "rb")}

我几乎总是从 Messenger 收到此响应错误:

'{"error":{"message":"(#100) param recipient must be non-empty.","type":"OAuthException","code":100,"fbtrace_id":"xxxxx"}}'

我在这里不知所措。我可能以某种方式滥用了 Requests 语法,或者向 API 发送了格式不正确的字符串,但我已经阅读了 Requests 文档并浏览了 StackOverflow 的问题,但无法解决我的问题。谢谢。

【问题讨论】:

  • 文件变量必须是字典,而不是元组数组。
  • 如果您确信这是问题所在,您能否在答案中提供示例代码?我已经尝试过使用字典。语法是:files = {“recipient”:收件人,“message”:消息,“filedata”:open(imagePath,“rb”)}
  • 感谢您发布您的问题。它帮助我调试了对营销 api 的类似 POST 请求!
  • 乐于助人。 :)

标签: python facebook curl python-requests messenger


【解决方案1】:

我认为问题在于您试图在请求文件 kwarg 中发送 formdata,而它应该在数据中:

data = {
    'recipient': '{"id":"USER_ID"}',
    'message': '{"attachment":{"type":"image", "payload":{}}}'
}
files = {
    "filedata": open(imagePath, 'rb')
}
r = requests.post('https://graph.facebook.com/v2.6/me/messages?access_token=ACCESS_TOKEN', data=data, files=files)

一个假设是 imagePath 存在。

同样在 python 中,{} 表示 Set 如果它没有 key:value 对,所以在你的答案中,你传递了一个单元组的集合,其中有两个项目,字符串filedatafile object

{("filedata", open(imgName, 'rb'))} # Set of tuple
{"filedata": open(imgName, 'rb')}   # dictionary

【讨论】:

  • 嗨 miah,你是绝对正确的,参见我上面的回答。我会将您的标记为正确,因为它看起来更漂亮。此外,特别是对于 Messenger API,必须指定文件类型: files = { "filedata" : ('filename.png', open(imagePath, 'rb'), 'image/png') }
【解决方案2】:

这是正确的格式:

imgName = "tmp/graph.png"
files = { "filedata" : ('filename.png', open(imagePath, 'rb'), 'image/png')}   
data = {
    "recipient":'{"id":"' + id + '"}',
    "message":'{"attachment":{"type":"image", "payload":{}}}'
    }

r = requests.post('https://graph.facebook.com/v2.6/me/messages?access_token=' + ACCESS_TOKEN, files=files, data=data)

【讨论】:

  • 可以打印imagePath吗?
  • 添加到答案中。它只是当前目录中的文件名。变量名“imagePath”有误导性,我重命名了。
猜你喜欢
  • 2011-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多