在Django Rest Framework中包含位置头

p5fdfcr1  于 2023-11-20  发布在  Go
关注(0)|答案(3)|浏览(105)

我在一篇文章中读到,这是理想的,把它是一个很好的标准,包括一个位置头指向新资源的URL(通过POST新创建)。我的问题是我不知道如何包括它。
我使用的是基于类的视图,使用的是APIView,我在视图中的代码是:

class ListArtists(APIView):
    serializer_class = ArtistSerializer
    def get(self, request, format=None):
        _array = Artist.objects.filter()
        serializer = self.serializer_class(_array, many=True)
        if serializer.data:
            _status = status.HTTP_200_OK
        else:
            _status = status.HTTP_204_NO_CONTENT
        return Response(standardResponse(data=serializer.data), status=_status)

    def post(self, request, format=None):
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(standardResponse(data=serializer.data), status=status.HTTP_201_CREATED)
        else:
            return Response(standardResponse(errors=serializer.errors))
artist = ListArtists.as_view()

字符串
urls.py

from django.conf.urls import url, include

from store import views

urlpatterns = [
    url(r'^artists/', views.artist, name='artists-list'),
]


P.S.
每次我使用高级REST客户端抛出请求时,这是我收到的响应:

Date: Sat, 23 Jul 2016 10:54:23 GMT
Server: WSGIServer/0.1 Python/2.7.10
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN
Content-Type: application/json
Allow: GET, POST, HEAD, OPTIONS

flmtquvp

flmtquvp1#

您可以向Response对象添加任意头,如下所示:

def post(self, request, format=None):
    serializer = self.serializer_class(data=request.data)
    if serializer.is_valid():
        obj = serializer.save()
        response = Response(standardResponse(data=serializer.data), 
                            status=status.HTTP_201_CREATED)
        # If you have defined a get_absolute_url method on your model, then
        # you can use that to get a URL for the new object
        response['Location'] = obj.get_absolute_url()
        return response

字符串

vvppvyoh

vvppvyoh2#

对于那些使用drfCreateModelMixin的人来说,view必须看起来像这样:
如果你想在响应中使用一个空的body:

class MyView(mixins.CreateModelMixin, generics.GenericAPIView):

    serializer_class = MySerializer

    def post(self, request, *args, **kwargs):
        default_response = self.create(request, *args, **kwargs)
        return Response(headers={'Location': reverse("get_enpoint_name", args=[default_response.data['id']], request=self.request)})

字符串
如果响应体必须包含序列化器中指定的对象数据:

class MyView(mixins.CreateModelMixin, generics.GenericAPIView):

    serializer_class = MySerializer

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

    def get_success_headers(self, data):
        try:
            return {'Location': reverse("customer", args=[data['id']], request=self.request)}
        except (TypeError, KeyError):
            return {}


总是开放的改进!

kyvafyod

kyvafyod3#

CreateModelMixin中的create-函数的默认值调用self.get_success_headers(serializer.data)(在这里实现)。
我们可以看到,默认情况下,api_settings.URL_FIELD_NAME将被包括在内。URL_FIELD_NAME默认情况下是url
例如,当在settings.py中将此值更改为id时,现在将在Location头中包含id

REST_FRAMEWORK = {
    "URL_FIELD_NAME": "id",  # This field is used in the Location header on a created resource
}

字符串
结果POST请求:

HTTP 201 Created
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Location: fe36f285-ab38-4ef9-b707-425f03a7cdc5
Vary: Accept

{
    "id": "fe36f285-ab38-4ef9-b707-425f03a7cdc5",
}

相关问题