gpt4 book ai didi

python - Django-Rest-Framework APIView 返回模型对象和图像

转载 作者:行者123 更新时间:2023-11-28 21:02:56 27 4
gpt4 key购买 nike

假设我想在 APIView.get 中返回一个包含 2 个属性的(非模型)对象,其中一个是模型对象,另一个是二进制图像

我尝试了几种方法,但在序列化程序方面遇到了问题。

谢谢!

序列化器:

class MyCustomSerializer(serializers.ModelSerializer):
class Meta:
model = MyCustom
fields = '__all__'

查看:

class MyCustomGet(APIView):
def get(self, request, format=None):
serializer = MyCustomSerializer
obj = s.get_custom()
return Response({"obj": serializer(obj.obj).data, "image": obj.image})

获取自定义:

class CustomClass:
obj = None
image = None

def get_custom():
r = CustomClass()
r.obj = MyCustom.objects.all().first()
r.image = PIL.Image.open('file/path.png')
return r

最佳答案

您正在尝试在 JSON 响应(字符串)中呈现图像(二进制数据)。这是行不通的。如果要以 JSON 字符串传递图像,则必须将其编码为字符串,然后在客户端对其进行解码。一个常见的例子是 base64 编码的字符串:

import io
import base64

...
def get_custom():
...
image = PIL.Image.open('file/path.png')
stream = io.StringIO()
image.save(stream, format='PNG')
return base64.b64encode(stream.getvalue())

虽然对您的 REST 端点设计一无所知,但我认为更好的解决方案是声明一个具有单独 View 的子资源。假设您的 REST 架构中有一个 MyCustom 资源,可通过 api/mycustom/:id/ 访问并由 MyCustomGet View 提供服务,例如一个单独的 View 可能负责在 api/mycustom/:id/pic/ 下提供相应的文件:

import django.http

class MyCustomPicView(APIView):
def get(self, request):
...
image = PIL.Image.open('file/path.png')
return django.http.HttpResponse(image, content_type='image/png')

关于python - Django-Rest-Framework APIView 返回模型对象和图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47309365/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com