Python:curl -F等价于Requests或其他

时间:2016-09-19 00:11:10

标签: python facebook curl python-requests messenger

我想重现以下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的相关问题并且无法解决我的问题。谢谢。

2 个答案:

答案 0 :(得分:1)

这是正确的格式:

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)

答案 1 :(得分: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