gpt4 book ai didi

python - 限制访问 Django 中的私有(private)文件下载

转载 作者:太空狗 更新时间:2023-10-29 17:30:12 24 4
gpt4 key购买 nike

我的 django 应用程序中有多个 FileField,它们可以属于不同的用户。我正在寻找一种好方法来限制非文件所有者的用户访问文件。

实现此目标的最佳方法是什么?有什么想法吗?

最佳答案

不幸的是@Mikko 的解决方案实际上不能在生产环境中工作,因为 django 不是为文件服务而设计的。在生产环境中,文件需要由您的 HTTP 服务器(例如 apache、nginx 等)提供,由您的应用程序/django 服务器(例如 uwsgi、gunicorn、mod_wsgi 等)提供。

这就是为什么限制文件访问不是很容易:您需要一种方法让您的 HTTP 服务器询问应用程序服务器是否可以向请求它的特定用户提供文件。如您所知,这需要修改您的应用程序您的 http 服务器。

上述问题最好的解决方案是django-sendfile(https://github.com/johnsensible/django-sendfile),它使用X-SendFile机制来实现上述。我正在从项目描述中复制:

This is a wrapper around web-server specific methods for sending files to web clients. This is useful when Django needs to check permissions associated files, but does not want to serve the actual bytes of the file itself. i.e. as serving large files is not what Django is made for.

要了解更多关于senfile机制,请阅读这个答案:Django - Understanding X-Sendfile

2018 更新:请注意 django-sendfile 似乎不再维护;可能它应该仍然有效,但是如果您想要一个具有类似功能的更现代的软件包,请查看 https://github.com/edoburu/django-private-storage正如评论者@surfer190 所建议的那样。特别要确保您实现了“优化大文件传输”部分;实际上,您不仅需要大文件的所有传输都需要它。

2021 更新:我回到这个答案是为了指出,虽然它已经有 4 年没有更新了,但 django-sendfile 项目仍然适用于当前的 Django 版本( 3.2),我实际上将它用于我所有需要该特定功能的项目!现在还有一个积极维护的 fork ,django-sendfile2 ,改进了 Python 3 支持和更广泛的文档。

关于python - 限制访问 Django 中的私有(private)文件下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28166784/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com