Django - DRF - dispatch method flow

谁都会走 提交于 2019-12-31 07:26:06

问题


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:


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.



来源:https://stackoverflow.com/questions/33740697/django-drf-dispatch-method-flow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!