瓶子 pandas return xls 文件

bottle pandas return xls file

是否可以在 bottle 中定义一个路由 return 一个文件?

  1. 我有一个 mongo 数据库,由 pandas 访问。
  2. Pandas根据请求参数生成xls文件。

以上两个步骤很清楚,也很容易实现。 第三步是我遇到的问题。

  1. 定义一个 bottle 路径,它将 return 一个文件供用户下载。

我不想使用以前生成的静态文件。

提前致谢。

我不熟悉 Pandas 但您需要获取 xls 文件的二进制内容以通过 Bottle 路由发送给用户。 here 的修改示例 Python 3:

from io import BytesIO
from bottle import route, response
from pandas import ExcelWriter


@route('/get-xlsx')
def get_xlsx():
    output = BytesIO()
    writer = ExcelWriter(output, engine='xlsxwriter')
    # Do something with your Pandas data
    # ...
    pandas_dataframe.to_excel(writer, sheet_name='Sheet1')
    writer.save()
    response.contet_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    response.add_header('Content-Disposition', 'attachment; filename="report.xlsx"')
    return output.getvalue()

当用户单击与此路线对应的 link 时,"report.xlxs" 的文件下载对话框将在他们的浏览器中打开。