首页 > 解决方案 > 在使用 Flask uwsgi 提供 PIL 图像时尝试隐式序列转换

问题描述

我正在通过 Flask 提供 PNG 或 SVG 图像。在本地它工作正常,但是当我在 docker 内运行应用程序并发送请求(POST)时,我收到以下错误:

RuntimeError: Attempted implicit sequence conversion but the response object is in direct passthrough mode.

通过烧瓶提供 PIL 图像的波纹管代码:

def serve_image(image: Image, mime_type: FileFormat, download: bool):
    suffix = mime_type.value.split('/')[-1]
    temp_file = tempfile.TemporaryFile(mode='w+b', suffix=suffix)
    if suffix == 'png':
        image.save(temp_file, suffix)
    else:
        # we cant force svg extension in PIL
        image.save(temp_file)
    temp_file.seek(0, 0)
    return send_file(temp_file, mimetype=mime_type.value, as_attachment=download,
                    attachment_filename='img.' + suffix)

我尝试过使用 BytesIO 也没有运气。环境

Response.implicit_sequence_conversion = False
Response.direct_passthrough = False

或者

@app.after_request
def after_request_func(r):
    r.direct_passthrough = False
    r.implicit_sequence_conversion = False
    return r

也没有帮助。

标签: pythondockerflaskpython-imaging-libraryuwsgi

解决方案


问题出在 openapi-core Flask 验证中,通过创建werkzeug Response 并将 direct passtrough 设置为 False 解决了这个问题。必须手动设置附件缓存超时等其他标头。

res = Response(temp_file, direct_passthrough=False, mimetype=mime_type.value)


推荐阅读