How to to make a file private by securing the url that only authenticated users can see

前端 未结 3 1817
花落未央
花落未央 2020-12-08 16:43

I was wondering if there is a way to secure an image or a file to be hidden when it is not authenticated.

Suppose there is an image in my website which can only be s

3条回答
  •  死守一世寂寞
    2020-12-08 17:44

    The easiest option is to serve the file from django, and then add the @login_required decorator to the view, like this:

    import os
    import mimetypes
    from django.core.servers.basehttp import FileWrapper
    from django.contrib.auth.decorators import login_required
    
    @login_required
    def sekret_view(request, path=None):
       filename = os.path.basename(path)
       response = HttpResponse(FileWrapper(open(path)),
                               content_type=mimetypes.guess_type(path)[0])
       response['Content-Length'] = os.path.getsize(path)
       return response
    

提交回复
热议问题