Python telegraph api. I can't understand how send image to telegraph via Python lib

China☆狼群 提交于 2021-02-11 14:12:24

问题


I'm trying to upload a photo from my hard drive to the telegraph. In the documentation it says to use the upload_file():

telegraph.upload.upload_file(f) Upload file to Telegra.ph’s servers. Returns a list of links. Allowed only .jpg, .jpeg, .png, .gif and .mp4 files. Parameters: f (file, str or list) – filename or file-like object.

But I don't understand what "f (file, str or list) – filename or file-like object" means. That is, what do I need to do with the photo so that it can be passed to this function

my attempts to solve the problem:

upload_file(open('1.png', 'rb'))

error: telegraph.exceptions.TelegraphException: File type invalid

myf = io.StringIO()
        myf.write(open(f'photo/{i}.png', 'rb'))
        print(upload_file(myf))
        myf.close()

error: TypeError: string argument expected, got '_io.BufferedReader'


回答1:


I am loading images using this method

  
def upload_image_telegraph(path_image):
    with open(path_image, 'rb') as f:
        result_requests = requests.post(
            'http://telegra.ph/upload',
            files={'file': ('file', f, 'image/jpg')}  # image/gif, image/jpeg,image/jpg, image/png, video/mp4
        ).json()
        return result_requests

You can also download using the library Python html_telegraph_poster With its help you can transfer both local images and a link to them Exemple

  
from html_telegraph_poster import upload_image
res = upload_image('local path image or link image') 


来源:https://stackoverflow.com/questions/64177086/python-telegraph-api-i-cant-understand-how-send-image-to-telegraph-via-python

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