使用序列化程序从URL保存图像

时间:2017-08-02 14:46:39

标签: python django http request django-rest-framework

我正在创建一个API,用于在django模型中保存图像。通过API发送一个URL,django负责下载图像并将其保存在模型中。

这是我的模特:

class Picture(Media):
    image = models.ImageField(upload_to=picture_path, blank=True, null=True)
    entity = models.CharField(max_length=20, choices=ENTITIES,
                          default=ENTITY_CLASIFICADO)

这是我的序列化器:

class PictureSerializer(serializers.ModelSerializer):
    image = serializers.ImageField(max_length=None, use_url=True)

    class Meta:
        model = Picture
        fields = ("pk", "image", "entity",)

从URL我生成一个PIL对象。如何指定存储对象的序列化程序?我的views.py

class PictureViewSet(generics.ListCreateAPIView):
    def create(self, request, *args, **kwargs):
        r = requests.get(request.data["url"])
        img_temp = NamedTemporaryFile(delete = True)
        img_temp.write(r.content)

现在,我正在保存空图像区域。

serializer = self.get_serializer(data=request.data)

我想将PIL对象添加到request.data,它看起来像这样:

<QueryDict: {'url': ['https://s3.amazonaws.com/cat/encabezado.jpg'], 'image': ['MY PIL IMAGE'], 'entity': ['clasificado'], 'csrfmiddlewaretoken': ['JRMLIXkxqg6sF5YP19NLTvgFOmVWH9ARSmM']}>

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以直接在序列化器中执行此操作 所以基本上它是现实生活中的工作示例,请注意我们需要在attrs中设置图像时将其设置为相对路径。
你还需要检查响应的状态,但我会留给你)

import os, uuid, requests
from django.conf import settings
from rest_framework.serializers import ModelSerializer
from .models import Audio

class AudioCreateSerializer(ModelSerializer):
    class Meta:
        model = Audio
        fields = ['image']

    def validate(self, attrs):
        url = "http://youurlgoeshere.com/sddsjdsjdsjds.png"
        data = requests.get(url)
        response = requests.get(image_url)
        random_name = uuid.uuid4().hex + ".png"
        folder_name = "custom_images"
        absolute_file_path = os.path.join(settings.MEDIA_ROOT, folder_name, random_name)
        relative_path = os.path.join(folder_name, random_name)
        with open(absolute_file_path, 'wb') as f:
            f.write(response.content)
        attrs['image'] = relative_path
        return attrs

另外,我将离开这里如何定义视图

class AudioListView(ListCreateAPIView):
    renderer_classes = [JSONRenderer]
    queryset = Audio.objects.select_related("artist")

    def get_serializer_class(self):
        if self.request.method == "GET":
            return AudioListSerializer
        if self.request.method == "POST":
            return AudioCreateSerializer