Django - DRF - dispatch method flow

2019-03-04 01:37发布

I am working with DRF to build an API and I used a master class to do some validations to my class based views:

class MasterClass(APIView):

    def dispatch(self, request, *args, **
        response = super(FaveoAPIView, self).dispatch(request, *args, **kwargs)
        # I call super because I need access to request data.
        # <some validations here>
        # Return a JsonResponse with an error message if validations fails

class MyView(MasteClass):

    def post(self, request, *args, **kwargs):
        # At this point request is: <WSGIRequest: POST '/api/path/'>
        # some DB transaction
        # ...

Validations are failing, at least one, but the DB transaction is being executed, I actually get a response with an error message from dispatch method, but post method is executed before dispatch, I use breakpoints to view the flow, and this is going into the post method and then to dispatch method, like if they were separated threads.

From docs:

The as_view entry point creates an instance of your class and calls its dispatch() method. dispatch looks at the request to determine whether it is a GET, POST, etc, and relays the request to a matching method if one is defined, or raises HttpResponseNotAllowed if not.

So I thought that if I return a response with an error in dispatch, post method shouldn't be executed, why is it being executed? What am I doing wrong here?

1条回答
看我几分像从前
2楼-- · 2019-03-04 02:11

Since you didn't provide the dispatch method code it'll just be guesses. My 2 cents is that you're calling MasterClass's super at some point which will call the APIView dispatch which will call your POST.

查看更多
登录 后发表回答