Post request handling in Django Rest framework
Asked Answered
S

1

5

I am using Django Rest Framework, currently to pull some data from the backend we are using Get request, but due to URL limit going high we are planning to implement a Post request. To do this firstly the backend Django Rest API has to be made available to serve a post request.

I am new to Django and I don't find a post or get method in the code, all i can say is we are using viewsets, I tried using "@detail_route(methods=['post'])" but this didn't work, what am I doing wrong here?

class XViewSet(viewsets.ViewSet):
    renderer_classes = ''

    def retrieve(self, request, pk=None):
        try:
            pk = int(pk)
        except ValueError:
            raise InvalidParameterError(parameter_name='id', invalid_value=pk)

        queryset = models.X.objects.all()
        x = get_object_or_404(queryset, pk=pk)

        pipelines = request.query_params.getlist('pipeline[]')

        callsets =

        callset_ids =

        serializer = serializers.XSerializer(x, context={'request': request})

        requested_samples = [z[1:] for z in request.query_params.getlist('s')]

        filtered_calls = []
        serialized_data = serializer.data

        unfiltered_calls = serialized_data.get('calls')
        if unfiltered_calls:
            for serialized_calls in unfiltered_calls:
                if serialized_calls['callset'] in callset_ids:
                    unfiltered_calls = serialized_calls['data']

                    for call in unfiltered_calls:
                        if call['y'] in requested_y:
                            filtered_calls.append(call)

                    break

        serialized_data['calls'] = filtered_calls

        return Response(serialized_data, status=status.HTTP_200_OK)

    def list(self, request):

        qp = self.request.query_params

        validated_qp =

        # generate the query
        query_object =
        query =

        # execute the query
        cursor = connections['default'].cursor()
        cursor.execute(query)

        qs = utils.dictfetchall(cursor)

        # sanitize query results
        if 't' in validated_qp:
            return_data =
        else:
            for x in qs:
                if 'calls' in x:

                    x['calls'] =
                else:
                    x['calls'] = {}

            return_data =

        resp = Response(return_data, status=status.HTTP_200_OK)

        if validated_qp.get(''):
            resp['content-disposition'] =

        return resp
Synopsis answered 21/2, 2018 at 9:4 Comment(3)
Show your views as example.Attitudinize
Please provide an example and show us how and where your method is failing.Monomial
updated with codeSynopsis
B
9

You can use class-based views to handle the requirements,

from rest_framework.views import APIView


class MyAPI(APIView):
    def get(selfself, request):
        # do stuff with get
        return Response(data="return msg or data")

    def post(self, request):
        post_data = request.data
        # do something with `post_data`
        return Response(data="return msg or data")



UPDATE : Using ViewSet
ViewSet class provide us create() methode to create new model instances. So we can override that to handle post data coming to the view. Just add a create() under your view class as below

class XViewSet(viewsets.ViewSet):
    renderer_classes = ''

    def create(self, request): # Here is the new update comes <<<<
        post_data = request.data
        # do something with post data
        return Response(data="return data")

    def retrieve(self, request, pk=None):
        # your code

        return Response(serialized_data, status=status.HTTP_200_OK)

    def list(self, request):
        # your code
        return resp
Burnell answered 21/2, 2018 at 9:8 Comment(8)
As said how can I implement a post method if I use viewsets not APIViews.Synopsis
@RealHead Updated the answer, please have a lookBurnell
Exactly what I asked for. Thanks.Synopsis
Also, if I send parameters in the body of the post request, how can i access them in the backend? Does request.data provide this data?Synopsis
Yes. request.data holds the whole content. Just use print() to verify thatBurnell
But response.data throws exception django.http.request.RawPostDataException: You cannot access body after reading from request's data streamDoormat
@Yougesh Did I mention response.data in my answer?Burnell
@JerinPeterGeorge sorry its request.data, typo mistake, but I have resolved that, that issue occurred because of debug point, anyway thanksDoormat

© 2022 - 2024 — McMap. All rights reserved.