Django:限制对未登录用户的静态文件夹访问

时间:2017-04-07 06:38:35

标签: python django apache mod-wsgi wsgi

我正在尝试限制那些直接在浏览器中访问绝对静态图片网址(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有关。 并且b / w静态和媒体内容也存在差异。我的问题只与静态内容有关

1 个答案:

答案 0 :(得分:4)

您可以通过将static url请求路由到您自己的视图(它尝试使用几乎所有网络服务器中都可用的sendfile扩展名)或使用django here来尝试我的回答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文件块api直接提供文件(大文件)在生产时不是一个好主意(想法如file.read()或FileResponse)

相关问题