[PYTHON] django + nginx How to make images viewed only by logged-in users

When combining django and nginx The method is to extract static files such as images with collectstatic and place them in nginx.

However, if you place it in ** nginx, you can see the static files without logging in to the system **, so ** This method can be used with the requirement that you want to deliver images that you want to limit to logged-in users **.

Premise

nginx → uwsgi → django You can access django from nginx.

Method

How to create a view for an image URL in django. Since it goes through django's view, you can only access it by logging in to the system.

file organization

projectroot
  + projectname
    + settings.py
  + media
    + pictures
      + test.jpg
  + testapp
    + urls.py
    + views.py

Define a view to access files in media in an application in django called testapp.

Source code

settings.py


MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

views.py


from django.http import HttpResponse
import os
from projectname import settings


def picture(request, imgfilename):
    file_path = os.path.join(settings.MEDIA_ROOT , 'pictures/' + imgfilename)

    with open(file_path, "rb") as f:  #rb stands for read binary
        imgfile = f.read()
    return HttpResponse(imgfile , content_type="image/jpeg")

urls.py


urlpatterns = [
    path('media/<imgfilename>', views.picture, name='picture'),
]

access

http://localhost:ポート/testapp/media/test.jpg

Recommended Posts

django + nginx How to make images viewed only by logged-in users
How to make only one data register on the Django admin screen
A memorandum to make WebDAV only with nginx
[Django] How to get data by specifying SQL.
Inspired by "How to make pure functional JavaScript"
[Continued] Inspired by "How to make pure functional JavaScript"
How to use Decorator in Django and how to make it
[Django] How to redirect unlogged-in users to the login page
Django Make choices only for the facility you belong to
How to make a Japanese-English translation
[Django] How to test Form [TDD]
How to make a slack bot
How to make a crawler --Advanced
How to make a recursive function
How to reflect CSS in Django
How to get started with Django
How to make a deadman's switch
[Blender] How to make a Blender plugin
[Blender] How to make Blender scripts multilingual
How to write Django1.9 environment-independent wsgi.py
How to make a crawler --Basic
How to log in to Docker + NGINX
How to authenticate with Django Part 2
How to authenticate with Django Part 3
How to make a process thread run only on a specific CPU core
[Rails] How to detect radical images by analyzing images using Cloud Vision API