twython从tempfiles上传媒体



所以我写了一个机器人,它从维基百科中提取图像(带请求)并将其发布到推特上(带twython)。我发现了这一点,这让我相信我可以做一些类似的事情

import tempfile
import twython
import requests
...
    req = requests.get(img_url, stream=True)
    with tempfile.TemporaryFile() as img_file:
        for chunk in req:
            img_file.write(req)
        resp = twython_client.upload_media(media=img_file)
    return resp['media_id']

但是upload_media调用抛出400。类似的东西

    ...
    with open('tmp_img_file', 'wb') as img_file:
        for chunk in req:
            img_file.write(chunk)
    with open('tmp_img_file', 'rb') as img_file:
        resp = twython_client.upload_media(media=img_file)
    os.remove('tmp_img_file')
    return resp['media_id']

可以工作,但"创建一个使用后立即删除的临时文件"不是临时文件的全部意义吗?我错过了什么/做错了什么?

写入会推进文件位置,因此必须执行

with tempfile.TemporaryFile() as f:
    f.write(data_to_write)
    f.seek(0)
    read_data = f.read()

最新更新