0

So I was writing a bot that pulls images from wikipedia (with requests) and posts them to twitter (with twython). I found this, which led me to believe I could do something like

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']

But the upload_media call throws 400s. Something like

    ...
    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']

does work, but isn't "creating a temporary file that gets deleted immediately after use" the whole point of tempfiles? What am I missing/doing wrong?

Community
  • 1
  • 1
swizzard
  • 1,037
  • 1
  • 12
  • 28

1 Answers1

0

Writing advances the file position, so you have to do

with tempfile.TemporaryFile() as f:
    f.write(data_to_write)
    f.seek(0)
    read_data = f.read()
swizzard
  • 1,037
  • 1
  • 12
  • 28