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

查看:109
本文介绍了在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对象的内容返回给mimetype设置为 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天全站免登陆