Pregunta

Here is the situation:

I use PIL to process an image, then I save it to a StringIO object. Now, I want to POST the StringIO object through poster. But, I can't get the image in the request.FILES dict. I have googled for a few hours, I found this question, python : post data within stringIO through poster? I tried but don't work.

So, I read the poster source code and found it try to get the 'name' attribution of the file-like object param, but it seems like StringIO object doesn't have the 'name' attribution, So, the filename and filetype are None

if hasattr(value, 'read'):
    # Looks like a file object
    filename = getattr(value, 'name', None)
    if filename is not None:
        filetype = mimetypes.guess_type(filename)[0]
    else:
        filetype = None

    retval.append(cls(name=name, filename=filename,
        filetype=filetype, fileobj=value))
else:
    retval.append(cls(name, value))

So, I specify the name attribution of StringIO object and it seems work fine.

im_tmp = Image.open(StringIO(bits))
//bits: the binary chars of a image
im_res = ImageAPI.process(im_tmp, mode, width, height)
//ImageAPI: a class that use PIL methods to process image
output = StringIO()
im_res.save(output, format='PNG')
output.name = 'tmp.png'
//I add above code and it works
call(url_str=url, file_dict={'file':output})
//call: package of poster

Did I do right? what's the right way to POST a StringIO object through poster?

¿Fue útil?

Solución

According to this commit, making the name optional was done explicitly to support passing in a StringIO object, but as you discovered that then skips detecting the mime type and defaults to text/plain instead.

Your approach then, is entirely correct. Simply set the .name attribute to goad poster into detecting a mime type.

The alternative is to use a better library to POST to the web. I recommend you look at requests, which supports multipart POSTing of files out of the box, including a way to set the filename. The mimetype will be based on that explicit filename if passed in.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top