Python请求:使用Multipart/form-data在Facebook上发布图像 [英] Python Request: Post Images on Facebook using Multipart/form-data
问题描述
我正在使用facebook API在页面上发布图像,我可以使用以下方法在网络上发布图像:
I'm using the facebook API to post images on a page, I can post image from web using this :
import requests
data = 'url=' + url + '&caption=' + caption + '&access_token=' + token
status = requests.post('https://graph.facebook.com/v2.7/PAGE_ID/photos',
data=data)
print status
但是当我要发布本地图像(使用multipart/form-data)时,出现错误: ValueError:数据不能为字符串.
But when I want to post a local image (using multipart/form-data) i get the error : ValueError: Data must not be a string.
我正在使用以下代码:
data = 'caption=' + caption + '&access_token=' + token
files = {
'file': open(IMG_PATH, 'rb')
}
status = requests.post('https://graph.facebook.com/v2.7/PAGE_ID/photos',
data=data, files=files)
print status
我阅读了( Python请求:发布JSON和单个请求中的文件),可能无法同时发送包含多部分编码文件的数据和文件,因此我更新了代码:
I read (Python Requests: Post JSON and file in single request) that maybe it's not possible to send both data and files in a multipart encoded file so I updated my code :
data = 'caption=' + caption + '&access_token=' + token
files = {
'data': data,
'file': open(IMG_PATH, 'rb')
}
status = requests.post('https://graph.facebook.com/v2.7/PAGE_ID/photos',
files=files)
print status
但是这似乎不起作用,我得到了与上述相同的错误.
你们知道为什么它不起作用,也许是解决此问题的方法.
But that doesn't seem to work, I get the same error as above.
Do you guys know why it's not working, and maybe a way to fix this.
推荐答案
将 data
作为字典传递:
data = {
'caption', caption,
'access_token', token
}
files = {
'file': open(IMG_PATH, 'rb')
}
status = requests.post(
'https://graph.facebook.com/v2.7/PAGE_ID/photos',
data=data, files=files)
请求
无法从 application/x-www-form-urlencoded
编码的字符串.
requests
can't produce multipart/form-data
parts (together with the files you are uploading) from a application/x-www-form-urlencoded
encoded string.
使用字典存储POST数据还有一个额外的优点,即 requests
负责正确编码值;标题
特别是可能包含必须正确转义的数据.
Using a dictionary for the POST data has the additional advantage that requests
takes care of properly encoding the values; caption
especially could contain data that you must escape properly.
这篇关于Python请求:使用Multipart/form-data在Facebook上发布图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!