为什么 django 不能返回带有下载文件链接的纯文本响应?

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

我在 Django eksport 功能中,在自定义管理中。 因此,当请求从数据库获取所有内容时,我对必要的样本进行 ORM 查询 - 查询很繁重,但它工作正常,我立即获取数据,不再访问数据库。 然后是处理这些数据的功能,将其推到各处,进行处理,最后推入数据框 pandas 并写入 CSV 文件,并保存在目录中(在立即尝试提供给用户之前),该文件的重量约为280MB。 那么,实际的问题是什么呢,真实的文件保存得相对较快,但用户的响应可能要半小时左右,只是一个下载文件的链接。

def save_data_in_csv_file(df_jewelry):
    """write data

    Attributes:
    - df_jewelry: data frame pandas +- 1_300_000 rows.
    """

    download_folder = os.path.join(os.path.dirname(__file__), 'download_file')

    if not os.path.exists(download_folder):
        os.makedirs(download_folder)

    file_path = os.path.join(download_folder, 'output.csv')

    with open(file_path, 'wb') as file:
        df_jewelry.to_csv(file, index=False)

    download_link = (
        'path_to_file'
    )

    response_data = {
        'message': 'File save!',
        'download_link': download_link,
    }

    response = Response(response_data, status=201)
    return response

这是一个视图,它运行主脚本,从上面的代码中它只是获取响应,然后将其提供给用户。

class ExportView(APIView):
    # permission_classes = (IsAdmin,)

    def post(self, request):
        request = request.data

        if not request:
            return Response(
                {'error': 'in request incorrect data.'},
                status=status.HTTP_400_BAD_REQUEST
            )

        return get_product_list(request)

结果,它可以像这样挂起半个小时,当它最终给出时(这种情况并不总是发生),CPU被释放,但RAM没有被释放。

查询本身在非生成器上运行,以免承载整个查询,否则会占用大约 8 GB 空间

...
    for product in product_list.iterator(chunk_size=10000): # +- 156.000 data
        yield product

没有响应,在执行导出写入文件的数据的功能后,一切都运行,文件被保存,但最后一步,给出响应,运行时间非常长。

python django django-rest-framework response django-orm
1个回答
0
投票

如果您正在处理文件中的数百万行,请不要使用 ORM。 我重写了代码以使用原始 SQL,之后对用户的响应正常,没有奇怪的延迟和 cpu 消耗。 显然,垃圾收集器或 ORM 本身很难应对如此庞大的数据量。

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