LoginSignup
1
0

More than 3 years have passed since last update.

django + nginx ログイン済みユーザにのみ画像閲覧させる方法

Last updated at Posted at 2020-10-01

djangoとnginxの組み合わせの際、
画像などの静的ファイルをcollectstaticで取り出してnginxに配置する方法が取られます。

ただし、nginxに配置するとシステムにログインしなくても静的ファイルが見えるので、
ログイン済みのユーザに限定したい画像を配信したいという要件で使える方法です。

前提

nginx → uwsgi → django
という構成で、nginxからdjangoにアクセスできること。

方法

djangoに画像URL用のviewを作成する方法です。
djangoのviewを経由するため、システムにログインしないとアクセスできないという仕組みです。

ファイル構成

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

testappというdjango内アプリケーションにmedia内のファイルにアクセスするviewを定義します。

ソースコード

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はread binaryのこと
        imgfile = f.read()
    return HttpResponse(imgfile , content_type="image/jpeg")
urls.py
urlpatterns = [
    path('media/<imgfilename>', views.picture, name='picture'),
]

アクセス

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

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0