如何使用Django将CSV格式的Pandas Dataframe下载流式传输

时间:2019-03-29 02:23:41

标签: python-3.x pandas django-2.0

在django文档中,他们实现了流CSV下载,并且速度非常快。知道如何使该解决方案适应Pandas数据框吗?理想情况下,无需将文件写入磁盘?我的代码可以工作,但是与这里的Django解决方案相比非常慢:https://docs.djangoproject.com/en/2.1/howto/outputting-csv/

下面的代码同时实现了非流式传输的示例-如果您想查看非流式传输解决方案,请将流切换为False。

import io
import pandas as pd
import numpy as np
from django.http import StreamingHttpResponse, HttpResponse

def file_download(request):
    df = pd.DataFrame(np.random.randn(100000, 4), columns=list('ABCD'))
    stream = True
    if stream:
      sio = io.StringIO()
      workbook = sio.getvalue()
      response = StreamHttpResponse(workbook, content_type='text/csv')
      response['Content-Disposition'] = 'attachment; filename="stream_download.csv"'
      return response
    else:
      response = HttpResponse(content_type='text/csv')
      response['Content-Disposition'] = 'attachment; filename="no_stream_download.csv"'
      df.to_csv(path_or_buf=response, index=False)
      return response

0 个答案:

没有答案