使用Django REST框架Render返回图像 [英] Return image using Django REST framework Render

查看:103
本文介绍了使用Django REST框架Render返回图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Django REST Framework 上传了图片.现在,我尝试返回与响应相同的图像.

views.py

I uploaded images using Django REST Framework. Now I'm trying to return the same image as response.

views.py

class ImageUploadView(viewsets.ModelViewSet):
    queryset = ImageModel.objects.all()
    serializer_class = ImageSerializer

    def create(self, request, *args, **kwargs):
        userID = (request.data.get('userID'))
        serializer = self.get_serializer(data=request.data)
        if not UserModel.objects.filter(id=userID).exists():
            return Response(data={"detail": "Invalid UserID"})
        else:
            if serializer.is_valid():
                serializer.save()                
                return Response(ImageModel.objects.get(id=serializer.data['id']).image, content_type="image/png")
        return Response(data={"detail": "Serializer Error"})

通过使用上面的代码,我既没有得到有效的图像(它返回的是像图像一样的小方框),也没有错误
希望有人可以提供帮助,谢谢

By using the above code, I didn't get neither a valid image (it returns one small square box like image) nor an error
Hope someone can help ,Thanks

推荐答案

我遇到了同样的问题,花了几个小时解决这个问题.操作方法如下:

I had the same issue and spent hours on it and I came up with a solution. Here's how you do it:

首先,您需要创建一个称为自定义渲染器的东西.如果您想知道,这是链接到REST框架的渲染器文档.有关什么是渲染器以及如何制作自定义渲染器的更多信息.在这种情况下,我们必须为 .jpg .png 文件制作自定义渲染器.为此,我建议您创建一个名为 custom_renderers.py 的文件,并将以下代码复制到其中:

At first, you need to create something called custom renderers. Here's the link to the REST Framework's Renderers Documentation if you wanna know more about what renderers are and how to make custom renderers. In this case, we'll have to make custom renderers for .jpg and .png files. For this, I would suggest you create a file called custom_renderers.py and copy the following code into it:

from rest_framework import renderers

class JPEGRenderer(renderers.BaseRenderer):
    media_type = 'image/jpeg'
    format = 'jpg'
    charset = None
    render_style = 'binary'

    def render(self, data, media_type=None, renderer_context=None):
        return data

class PNGRenderer(renderers.BaseRenderer):
    media_type = 'image/png'
    format = 'png'
    charset = None
    render_style = 'binary'

    def render(self, data, media_type=None, renderer_context=None):
        return data

2.导入渲染器,并通过

将它们包括在您的视图中

此后,如果要使用基于类的渲染,则必须导入刚刚生成的渲染,并将其包含在视图中的属性 renderer_classes = [JPEGRenderer,PNGRenderer] 中视图(或者,如果您使用的是基于方法的视图,则必须将它们包括在装饰器 @renderer_classes()下)

2. Import the renderers and include them in your view by

After this, you've got to import the renders that you've just made and include them in your view within the attribute renderer_classes = [JPEGRenderer, PNGRenderer] if you are using class-based views (or if you are using method-based views, you've got to include them under the decorator @renderer_classes())

如果您要投放图片或视图中的任何图片,则必须先使用您图片对象旁边的 .open()打开图片或文件已作为查询的响应字段接收,然后在发送图像之前使用 FileWrapper()包裹图像(之所以这样,是因为您在响应中得到一个小的黑匣子,原因是我在发送图像之前没有打开图像,也没有使用过 FileWrapper()).因此,您的回应如下:返回响应(FileWrapper(ImageModel.objects.get(id = serializer.data ['id'])[[image'].open())

If you're serving an image or any kind of in your view, you've got to first open the image or the file by using .open() next to the image object that you've received as a response field of your query, and then use a FileWrapper() to wrap the image before you send it (The reason I was getting a small black box in the response just like you was that I had not opened the image before sending it and also hadn't used a FileWrapper()). So, your response goes like - return Response(FileWrapper(ImageModel.objects.get(id=serializer.data['id'])['image'].open())

我没有指定返回类型,因为在我的情况下返回类型是自动确定的.因此,您的 views.py 最终将类似于:

I did not specify the return type as the return type was automatically determined in my case. Therefore, your views.py will finally be like:

## All the other necessary imports

from path.to.custom_renderers import JPEGRenderer, PNGRenderer
from wsgiref.util import FileWrapper

#Also, I think this should rather be ImageDownloadView as the client would be downloading the image
class ImageUploadView(viewsets.ModelViewSet):
    renderer_classes = [JPEGRenderer, PNGRenderer]

    queryset = ImageModel.objects.all()
    serializer_class = ImageSerializer

    def create(self, request, *args, **kwargs):
        userID = (request.data.get('userID'))
        serializer = self.get_serializer(data=request.data)
        if not UserModel.objects.filter(id=userID).exists():
            return Response(data={"detail": "Invalid UserID"})
        else:
            if serializer.is_valid():
                serializer.save()                
                return Response(FileWrapper(ImageModel.objects.get(id=serializer.data['id'])['image'].open())
                # You can also specify the content_type in your response
        return Response(data={"detail": "Serializer Error"})

干杯!

这篇关于使用Django REST框架Render返回图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆