Django 返回大文件
我正在尝试找到将大文件从 Django 返回到 http 客户端的最佳方法(最有效的方法)。
- 接收http get请求
- 从磁盘读取大文件
- 返回该文件的内容
我不想读取该文件然后使用HttpResponse发布响应,因为如果我是正确的,文件内容首先存储在RAM中。我怎样才能有效地做到这一点?
洛朗
I am trying to find the best way (most efficient way) to return large files from Django back to an http client.
- receive http get request
- read large file from disk
- return the content of that file
I don't want to read the file then post the response using HttpResponse as the file content is first stored in RAM if I am correct. How can I do that efficiently ?
Laurent
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您喜欢使用 Django 进行身份验证,请查看 Apache 上的 mod_xsendfile(或 nginx 等的等效项)。否则,无需使用 django,只需直接从 Apache 进行服务器即可。
Look into mod_xsendfile on Apache (or equivalents for nginx, etc) if you like to use Django for authentication. Otherwise, there's no need to hit django, and just server straight from Apache.
这里有一张旨在解决此问题的票证: http://code.djangoproject.com/ticket /2131
它添加了一个 HttpResponseSendFile 类,该类使用 sendfile() 发送文件,该类在读取文件时透明地发送文件。
但是,标准 HttpResponse 是作为迭代器实现的,因此如果您向其传递一个类似文件的对象,它将遵循其迭代语义,因此大概您可以创建一个类似文件的对象包装器,在发送之前将文件分成足够小的块他们出去。
我相信在 python 中迭代标准文件对象的语义是它逐行读取,如果您正在处理二进制文件,这很可能无法解决您的问题。
当然,您始终可以将静态文件放在另一个位置,并使用普通的 Web 服务器来提供该文件,除非您需要复杂的控制(例如需要了解 Django 数据库的访问控制)
There is a ticket that aims to deal with this problem here: http://code.djangoproject.com/ticket/2131
It adds an HttpResponseSendFile class that uses sendfile() to send the file, which transparently sends the file as it's read.
However, the standard HttpResponse is implemented as an iterator, so if you pass it a file-like object, it will follow its iteration semantics, so presumably you could create a file-like object wrapper that chunks the file in small enough pieces before sending them out.
I believe the semantics of iterating over a standard file object in python is that it reads line-by-line, which most likely won't solve your problem if you're dealing with binary files.
Of course, you could always put the static files in another location and serve that with a normal web server, unless you require intricate control (like access control requiring knowledge of the Django database)
我对所有这些的偏好是将 django 与您的 http 服务器综合起来,这样当您想要提供静态文件时,您只需将它们引用到永远不会到达 django 的路径即可。该策略将如下所示:
My preference for all of this is to synthesize django with your http server so that when you want to serve static files, you simply refer them to a path that will never reach django. The strategy will look something like this:
HttpRedirect("/web-path/to/doc")
.