LoginSignup
0
0

More than 1 year has passed since last update.

Django REST frameworkでローカルの画像を返すAPIを作る

Posted at

概要

Django REST frameworkで画像を返すAPIを作成した。

実装

  • macOS Catalina(v10.15.7)
  • Python: 3.8

開発

はじめに、画像を保存するパスを指定する。例えばmedia/に保存する場合は、下記のように指定する。

settings.py
MEDIA_ROOT = os.join(Path(__file__).resolve().parent.parent, 'media')

画像を取得するAPIのエンドポイントを設定する。今回はエンドポイントをapi/v1/imageに指定する。

urls.py
from django.urls import path

from .views import ImageSet

urlpatterns = [
    ...省略...
    path("api/v1/image", ImageSet.get_image),
]

view.pyに画像を返す処理を作成する。media/${画像ファイル名}に保存されている画像に対して、/api/v1/image?image_url=${画像ファイル名}で画像のパスを指定して、画像を取得できるようにする。

views.py
import os

from django.conf import settings
from django.http import Http404, HttpResponse
from rest_framework.decorators import api_view
from rest_framework.request import Request

class ImageSet:

    @api_view(["GET"])
    def get_image(request: Request):
        # image_urlのクエリパラメータから画像のパスを取得する
        image_url = request.query_params.get("image_url", None)
        if not image_url:
            return Http404
        file_path = os.path.join(settings.MEDIA_ROOT, receipt_url)
    
        if not os.path.exists(file_path):
            return Http404
    
        with open(file_path, "rb") as fh:
            response = HttpResponse(fh.read(), content_type="image/png")
            return response

動作確認

settings.pyに指定したMEDIA_ROOT(今回であればmediaパス)にテスト用の画像を保存する。

  • media/test_image.jpg

その後、下記のURLにアクセスして画像が表示されていることを確認する。

0
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
0
0