首页 文章

Django的 . 推特图片保存在ImageField上

提问于
浏览
0

我想推特保存在模型的 ImageField 上的图像 . 我正在使用 tweepy ,但我对任何可行的东西持开放态度 .

这就是我尝试过的:

First:

api = tweepy.API(auth)
api.update_with_media(filename=model_object.image.name, status=text, file=model_object.image)

错误:TweepError:图像的文件类型无效:无

Then:

from PIL import Image

api = tweepy.API(auth)
image_file = Image.open(model_object.image)
api.update_with_media(filename=model_object.image.name, status=text, file=image_file)

219,在update_with_media Headers 中,post_data = API._pack_image(文件名,3072,form_field ='media []',f = f)文件“/home/alejandro/Proyectos/criptohisoka/local/lib/python2.7/site- packages / tweepy / api.py“,第1311行,在_pack_image中f.seek(0,2)#寻找文件结束TypeError:seek()只取2个参数(给定3个)

Finally:

from PIL import Image
from StringIO import StringIO

api = tweepy.API(auth)
image_file = Image.open(model_object.image)
stringio_obj = StringIO()
image_file.save(stringio_obj, format="JPEG")
api.update_with_media(filename=model_object.image.name, status=text, file=stringio_obj)

TweepError:图像的文件类型无效:无

我不确定 update_with_media 方法对文件的期望 . 这是相关的 tweepy source code,这里是docs .

1 回答

  • 1

    由于 upload_with_media endpoints 已被弃用,请参阅here,我建议您使用以下方法:

    使用文件的绝对路径

    media_ids = api.media_upload(filename=model_object.image.file.name)
    

    Twitter API将使用 media_ids 变量中缓存的长整数进行响应 .

    最后,使用 update_status endpoints :

    params = {'status': 'chop chop chop', 'media_ids': [media_ids.media_id_string]}
    response = api.update_status(**params)
    

    供参考,请参阅tweepy中的方法定义,以及它们在Twitter api中的对应关系:

相关问题