自称フルスタックエンジニアのぶろぐ。

pythonやreactや、gcpやawsなどなどについて書いていこうかと思います。

python djangoで画像をmodelのImageFieldに保存する時の話。

画像を保存する場合のお話。

  • これに困った経緯 画像の保存先をgoogle cloud storageに保存したい。
    これってどこでどうすれば保存できるんだ・・・から始まった。

静的保存場所の設定

  • settingsにgoogle cloud storageの設定を追加
STATIC_URL = 'https://storage.googleapis.com/[プロジェクト名].appspot.com/static/'
DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage'
GS_BUCKET_NAME = '[プロジェクト名].appspot.com'
PROJECT_ID = '[プロジェクト名]'

を追加

  • モデルにimageの定義
class Image(models.Model):
    img = models.ImageField(null=True, blank=True, upload_to='img')
  • views
    今回はrest apiだったので、restのview
    base64で画像を受け取る想定
import base64, request
from django.core.files.base import ContentFile

class ImageViewSet(ModelViewSet):
    queryset = Image.objects.all()
    serializer_class = ImageSerializer

    def create(self, request, *args, **kwargs):
        data = request.data.get('img')
        if data:
            format, imgstr = data.split(';base64,')
            ext = format.split('/')[-1]
            request.data['img'] = ContentFile(base64.b64decode(imgstr), name='temp.' + ext)
        return super(ImageViewSet, self).create(request)

URLから取得した画像を保存したい時

import request
from .models import Image
from django.core.files.base import ContentFile

url = 'http://xxxxxxxxx/abc.jp'
file_name = 'img/{}'.format(urlparse(url).path.split('/')[-1]) 
response = requests.get(url)
image = Image()
image.img.save(file_name, ContentFile(response.content, file_name), save=True)

murabo.hatenablog.com

murabo.hatenablog.com