在 Django 中提供动态生成的 ZIP 档案 [英] Serving dynamically generated ZIP archives in Django

查看:34
本文介绍了在 Django 中提供动态生成的 ZIP 档案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Django 中为用户提供动态生成的 ZIP 存档?

How to serve users a dynamically generated ZIP archive in Django?

我正在制作一个网站,用户可以在其中选择可用书籍的任意组合并将它们下载为 ZIP 存档.我担心为每个请求生成这样的档案会减慢我的服务器的速度.我也听说 Django 目前没有一个很好的解决方案来提供动态生成的文件.

I'm making a site, where users can choose any combination of available books and download them as ZIP archive. I'm worried that generating such archives for each request would slow my server down to a crawl. I have also heard that Django doesn't currently have a good solution for serving dynamically generated files.

推荐答案

解决方案如下.

使用 Python 模块 zipfile 创建 zip 存档,但如文件指定StringIO 对象(ZipFile 构造函数需要类文件对象).添加要压缩的文件.然后在您的 Django 应用程序中返回 HttpResponse 中 StringIO 对象的内容,并将 MIME 类型设置为 application/x-zip-compressed(或至少 application/octet-stream).如果需要,您可以设置 content-disposition 标头,但这应该不是必需的.

Use Python module zipfile to create zip archive, but as the file specify StringIO object (ZipFile constructor requires file-like object). Add files you want to compress. Then in your Django application return the content of StringIO object in HttpResponse with mimetype set to application/x-zip-compressed (or at least application/octet-stream). If you want, you can set content-disposition header, but this should not be really required.

但要注意,在每个请求上创建 zip 档案是个坏主意,这可能会杀死您的服务器(如果档案很大,则不计算超时).性能方面的方法是将生成的输出缓存在文件系统的某处,只有在源文件发生更改时才重新生成它.更好的主意是提前准备档案(例如通过 cron 作业),并让您的网络服务器像往常一样为它们提供静态服务.

But beware, creating zip archives on each request is bad idea and this may kill your server (not counting timeouts if the archives are large). Performance-wise approach is to cache generated output somewhere in filesystem and regenerate it only if source files have changed. Even better idea is to prepare archives in advance (eg. by cron job) and have your web server serving them as usual statics.

这篇关于在 Django 中提供动态生成的 ZIP 档案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆