python - Django:限制非登录用户访问静态文件夹

标签 python django apache mod-wsgi wsgi

我试图限制那些直接在浏览器中点击绝对静态图像 url 路径 (www.xyz.com/static/img/sam.png) 并访问它的用户。

我尝试使用以下 Django 文档:

https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/apache-auth/

但这也会阻止登录页面中的那些图像(在验证有效用户之前)。

有没有其他有效的方法来限制未登录用户?

编辑: 我提到过这个 Django: Serving Media Behind Custom URL但它与 nginx 有关,与 apache 无关。 黑白静态内容和媒体内容也有区别。我的问题只与静态内容有关

最佳答案

你可以试试我的回答here通过将 static url 请求路由到您自己的 View (它尝试使用几乎所有 Web 服务器中可用的 sendfile 扩展名)或使用 django whitenoise , whitenoise 使用独立于服务器的 sendfile api(无论你使用的是 nginx 还是 apache)并且生产就绪,扩展 whitenoise middleware 并在那里添加你的文件限制检查,一个 sample 代码将是

  from django.http import HttpResponseForbidden
  from whitenoise.middleware import WhiteNoiseMiddleware
  # this is a sample code, you can change for your use case
  class ProtectedStaticFileMiddleware(WhiteNoiseMiddleware):
        def process_request(self, request):
            # check user authentication
            if condition_met(request):
               return super(WhiteNoiseMiddleware, self).process_request(request)
            # condition false
            return HttpResponseForbidden("you are not authorized")

注意:在生产中使用 python 文件 block api 直接提供文件(大文件)不是一个好主意(像 file.read() 或 FileResponse 这样的想法)

关于python - Django:限制非登录用户访问静态文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43271275/

相关文章:

python - 查找总和最接近给定数字的二维数组的路径

python - 机器学习 - 使用 sklearn

python - 类型错误 : __init__() missing 1 required positional argument: 'on_delete' (Django 2)

python - 如何在编辑表单中更改 ImageField 的 html 模板?

java - Apache James邮件服务器的优点和使用?

Linux 目录权限

python - 如何删除不同位置的两个斜杠

python - 当我在 python 中运行 cmd 时,cx_freeze 可执行文件不起作用

Python无法导入ssl模块

php - Android登录验证失败