flask_返回字节流错误

Posted lajiao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了flask_返回字节流错误相关的知识,希望对你有一定的参考价值。

# flask_返回字节流错误

def export_data(filename, fields, data, names=None, sheet=‘Sheet1‘):
    # fields 为list data为dict

    fp = io.BytesIO()
    book = xlsxwriter.Workbook(fp, {‘in_memory‘: True})
    worksheet = book.add_worksheet(sheet)
    # 表头格式
    format1 = book.add_format(
        {‘bold‘: True, ‘font_color‘: ‘black‘, ‘font_size‘: 13, ‘align‘: ‘left‘, ‘font_name‘: u‘宋体‘})
    # 表头外格式
    format2 = book.add_format({‘font_color‘: ‘black‘, ‘font_size‘: 9, ‘align‘: ‘left‘, ‘font_name‘: u‘宋体‘})
    # A列列宽设置能更好的显示
    worksheet.set_column("A:F", 20)
    # book = xlwt.Workbook()
    # worksheet = book.add_sheet(‘Sheet1‘)  # 创建一个sheet
    # 插入第一行表头标题
    if names:
        for i in range(0, len(names)):
            name = names[i]
            worksheet.write(0, i, name, format1)
    else:
        for i in range(0, len(fields)):
            field = fields[i]
            worksheet.write(0, i, field, format2)
    # 从第二行开始插入数据
    for i in range(len(data)):
        item = data[i]
        for j in range(len(fields)):
            field = fields[j]
            worksheet.write(i + 1, j, item[field])
    book.close()
    # fp.seek(0)

    # print(filename,‘////////////////////‘)
    name = parse.quote(filename)
    # print(fp.getvalue(),‘-------------------‘)
    # rv = send_file(send_file(fp, attachment_filename=‘%s.xlsx‘ % name, as_attachment=True))
    rv = make_response(fp.getvalue())
    # 特别注意,必须加这一行
    fp.close()
    mime_type = mimetypes.guess_type(‘%s.xlsx‘ % name)[0]
    rv.headers[‘Content-Type‘] = mime_type
    rv.headers["Cache-Control"] = "no-cache"
    rv.headers[‘Content-Disposition‘] = ‘attachment; filename={}.xlsx‘.format(name)

    return rv

# 报错信息:
"""
io.UnsupportedOperation: fileno
....

/python3.6/site-packages/werkzeug/wsgi.py", line 893, in wrap_file
    return environ.get(‘wsgi.file_wrapper‘, FileWrapper)(file, buffer_size)
SystemError: <built-in function uwsgi_sendfile> returned a result with an error set

原因:BytesIo未关闭,加上fp.close就行了
"""

以上是关于flask_返回字节流错误的主要内容,如果未能解决你的问题,请参考以下文章

php如何将图片转成字节流

IO编程__字节流__输入

IO编程__字节流__输出

IO编程__字节流__输入输出__图片移动

S3 对象返回八位字节流,但上传为 png

AJAX - 将返回的八位字节流转换为类型化数组 (Float64Array)