Pandas CSV 到 Django 响应

问题描述 投票:0回答:2

我有一个从数据库生成的 DataFrame。我如何提供下载 CSV 的响应?

基本上,

df = magic_dataframe_supplier()
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=export.csv'

# ... type mapping code ...

return response

我有一个带有

csv.writer
的工作版本,但出于明显的原因,这不是
DataFrame
。我不清楚如何将
df
变成这样的对象。

python django pandas
2个回答
20
投票

鉴于:

df = magic_dataframe_supplier()
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=export.csv'  # alter as needed

只需写:

df.to_csv(path_or_buf=response)  # with other applicable parameters
return response

Pandas 将数据帧写入响应缓冲区中的 CSV,然后 Django 提供响应。

压缩。 Pandas 不允许传递非无

compression
参数,因为它无法从缓冲区(不是路径)确定压缩类型。相反,为了压缩,必须将文件写入文本包装器,然后使用 Python 的
gzip
库进行压缩。然后该对象将被用作存档。类似于 this 的代码,适用于 Django,是必要的。

编辑。 2024年4月25日。我认为,但不确定,如果您的服务器正确配置了 Apache

mod_deflate
之类的东西,它会动态压缩您的文档并为其提供服务(尽管每次都会重新压缩)。


-2
投票

我相信JavaScript中不存在对象类型“DataFrame”。您可能想尝试使用 JSON 来传输数据。

© www.soinside.com 2019 - 2024. All rights reserved.