首页 > 解决方案 > Bottle web 框架:如何将 csv 文件返回给 Angular 客户端

问题描述

在瓶子网络框架中,我需要返回一个 csv 文件以从 Angular 客户端下载。

@route('/project/download')
def download_projects_result_file():
    #here i have a csv file in /tmp/proj_category.csv

    return ....?

如何将 csv 文件返回给客户端?

谢谢

标签: pythonpython-3.xflaskbottle

解决方案


你想在客户端加载文件的内容还是直接下载?

要直接下载,Content-Disposition请在瓶子响应中使用标头。

这是一个例子:

from bottle import LocalResponse, route

@route('/project/download')
def download_projects_result_file():
    with open('/tmp/proj_category.csv') as file:
        file.seek(0)
        byte_data = file.read()
        response = LocalResponse(
            body=byte_data,
            headers={
                "Content-Disposition": "attachment; filename='filename.csv'",
                "Content-Type": "text/csv",
            }
        )
        return response

推荐阅读