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?