提问者:小点点

DjangoRest框架-追加主机名到响应


当我要求一个图像http://127.0.0.1:8000/api/images/1/或者传入参数进行裁剪http://127.0.0.1:8000/api/images/1/?height=320

我得到的答复是:

   {
        "image": "/media/10438039923_2ef6f68348_c.jpg",
        "description": "Description 1",
        "title": "Item 1"
    }

而在http://127.0.0.1:8000/api/images/

答复是:

      {
            "title": "Item 1",
            "description": "Description 1",
            "image": "http://127.0.0.1:8000/media/10438039923_2ef6f68348_c.jpg"
        },
        {
            "title": "Item 2",
            "description": "Description 2",
            "image": "http://127.0.0.1:8000/media/ALLEY-stock1502.jpg"
        },

为什么缩略图不容易返回主机名,我如何将基本网址追加到响应中?

以下是我的看法。派克

from __future__ import unicode_literals
from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.response import Response
from .models import Image
from .serializers import ImageSerializer
from easy_thumbnails.files import get_thumbnailer


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

    def retrieve(self, request, pk=None):
        height = request.query_params.get('height', None)
        width = request.query_params.get('width', None)
        img = self.get_object()
        if height and width:
            options = {'size': (height, width), 'crop': True}
            thumb_url = get_thumbnailer(img.image).get_thumbnail(options).url
        else:
            thumb_url = get_thumbnailer(img.image).url
        serializer = self.get_serializer(img)
        response_dict = {}
        response_dict.update(serializer.data)
        response_dict['image'] = thumb_url
        return Response(response_dict)

共3个答案

匿名用户

主机名存储在HttpRequest中,因此您可以在响应中使用它。

见:https://docs.djangoproject.com/en/1.11/ref/request-response/#django.http.HttpRequest.META

匿名用户

正如Laurent LAPORTE所说,主机名存储在HttpRequest中。

但是要获得它,你不应该直接访问它,而是使用:

get_host()

否则,您将绕过安全保护。

见:https://docs.djangoproject.com/en/2.0/topics/security/#host-标题验证

匿名用户

或者在您的设置中,从

MEDIA_URL = '/media/'

MEDIA_URL = 'http://127.0.0.1:8000/media/'