【问题标题】:python POST a StringIO using posterpython 使用海报发布一个StringIO
【发布时间】:2013-07-15 08:05:27
【问题描述】:

情况如下:

我使用 PIL 处理图像,然后将其保存到 StringIO 对象。 现在,我想通过海报发布 StringIO 对象。 但是,我无法在 request.FILES 字典中获取图像。 我用谷歌搜索了几个小时,我发现了这个问题, python : post data within stringIO through poster? 我试过了,还是不行。

所以,我阅读了海报源代码,发现它试图获取类文件对象参数的“名称”属性,但似乎 StringIO 对象没有“名称”属性,所以,文件名和文件类型是无

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))

所以,我指定了 StringIO 对象的名称属性,它似乎工作正常。

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

我做对了吗?通过海报发布 StringIO 对象的正确方法是什么?

【问题讨论】:

    标签: python post stringio poster


    【解决方案1】:

    根据this commit,将名称设为可选明确以支持传入StringIO 对象,但正如您发现的那样,它会跳过检测mime 类型并默认为text/plain而是。

    那么,您的方法是完全正确的。只需将.name 属性设置为刺激poster 以检测mime 类型。

    另一种方法是使用更好的库来发布到网络。我建议您查看requests,其中supports multipart POSTing of files 开箱即用,包括设置文件名的方法。如果传入,mimetype 将基于该显式文件名。

    【讨论】:

    • 谢谢,但该项目正在使用海报,我无法更改结构。
    猜你喜欢
    • 2023-03-17
    • 2010-12-14
    • 1970-01-01
    • 2011-03-17
    • 2014-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多