Python requests: how to get and send an image without saving to disk?
The API I'm working on has a method of POSTing images to /api/pictures/
with an image file in the request.
I want to automate some sample images using the Python Query Library, but I'm not really sure how. I have a list of urls pointing to images.
rv = requests.get('http://api.randomuser.me')
resp = rv.json()
picture_href = resp['results'][0]['user']['picture']['thumbnail']
rv = requests.get(picture_href)
resp = rv.content
rv = requests.post(prefix + '/api/pictures/', data = resp)
rv.content
returns bytecode. I receive 400 Bad Request from the server, but no error message appears. I suppose I am either drawing "wrong" when I do rv.content
or sending it wrong with data = resp
. Am I on the right track? How do I send files?
- Edit -
I changed the last line to
rv = requests.post('myapp.com' + '/api/pictures/', files = {'file': resp})
Server side code (checkbox):
file = request.files['file']
if file and allowed_file(file.filename):
...
else:
abort(400, message = 'Picture must exist and be either png, jpg, or jpeg')
Server aborts status code 400 and message above. I also tried reading resp
from BytesIO, didn't help.
source to share
The problem is that your data is not a file but a stream of bytes. So it doesn't have a "filename" and I suspect your server code isn't working.
Try sending the correct filename along with the correct mime type with your request:
files = {'file': ('user.gif', resp, 'image/gif', {'Expires': '0'})}
rv = requests.post('myapp.com' + '/api/pictures/', files = files)
You can use imghdr
to figure out which image you are facing (to get the correct mime type):
import imghdr
image_type = imghdr.what(None, resp)
# You should improve this logic, by possibly creating a
# dictionary lookup
mime_type = 'image/{}'.format(image_type)
source to share