I would like to allow clients to send HTTP HEAD requests to my endpoint to allow them to check whether the resource exists without requiring the bandwidth to respond with the resource in the response body if it does. It should of course behave the same as GET but without sending the body of the response, just the header. I initially thought this would be handled by the DRF Router and ModelViewSet, but this question indicates that that isn't the case. Therefore I followed the advice in the answer posted there and wrote the following in urls.py and views.py:
project/urls.py
urlpatterns = [
path('api/resource/<str:value>', views.ResourceViewSet.as_view(actions={'head': 'retrieve', 'get': 'retrieve'})),
app/views.py
class ResourceViewSet(viewsets.ModelViewSet):
serializer_class = serializers.ResourceSerializer
queryset = Resource.objects.all()
lookup_field = 'value'
This setup isn't working for head requests. The get requests are all working as expected. Interestingly, the location and type of error I get depends on the client:
From Postman client I get Parse Error: The server returned a malformed response
in the Postman console. The DRF logs however show it giving the correct response code and there are no errors on the server.
From CURL I get the correct response in the client, but the server throws a reset error:
ConnectionResetError: [Errno 104] Connection reset by peer
I think that the problem is that I'm using the existing retrieve method in the view for HEAD requests. But I also can't think that I should need to write a new method from scratch when retrieve already has the header I need.
How can I implement this? Thanks.
question from:
https://stackoverflow.com/questions/65599348/how-to-create-route-and-view-for-head-http-verb-in-django-rest-framework 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…