Python Request: Post Images on Facebook using Multipart/form-data

不打扰是莪最后的温柔 提交于 2021-02-07 10:10:33

问题


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

But when I want to post a local image (using multipart/form-data) i get the error : ValueError: Data must not be a string.

I was using this code:

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

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.


回答1:


Pass in data as a dictionary:

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)

requests can't produce multipart/form-data parts (together with the files you are uploading) from a application/x-www-form-urlencoded encoded string.

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.



来源:https://stackoverflow.com/questions/38633791/python-request-post-images-on-facebook-using-multipart-form-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!