flask中send_file模块返回现生成的缓存文件流txt,不用先创建txt文件再读取

@app.route('/')
def index():
    file = BytesIO()
    file.write(('\n'.join([str(i)for i in range(0,10000)]).encode()))
    file.seek(0)
    return send_file(file, as_attachment=True,
                     attachment_filename"xxx.txt")

注意:

生成0-9999的文本

file.seek(0)一定要把指针移动到0,不然返回空文档

在返回的是txt,大家改下文件名,就可以直接生成不同格式文档,

格式比较复杂的话,加上

参数 mimetype='application/xxx.xxx'
就行了

猜你喜欢

转载自blog.csdn.net/m0_38124502/article/details/118019863