Django - DRF - 调度方法流程 [英] Django - DRF - dispatch method flow

查看:134
本文介绍了Django - DRF - 调度方法流程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与DRF建立一个API,我使用一个主类来对我的基于类的视图进行一些验证:

  class MasterClass(APIView):

def dispatch(self,request,* args,**
response = super(FaveoAPIView,self).dispatch(request,* args,**
#我调用super,因为我需要访问请求数据
#< some validationments here>
#如果验证失败,返回一个错误消息的JsonResponse

class MyView(MasteClass):

def post(self,request,* args,** kwargs):
#在这一点上,请求是:< WSGIRequest:POST'/ api / path /'>
#一些DB事务
#...

验证失败,至少有一个,但DB事务正在执行,我实际上收到一条来自 dispatch 方法的错误消息的响应,但 post 方法在 dispatch 之前执行,我使用断点查看流程,这将进入 post 方法,然后到 dispatch 方法,如他们是分开的线程。



docs


as_view入口点创建一个类的实例,并调用
它的dispatch()方法。调度查看请求以确定
是否是GET,POST等,并将请求中继到匹配的
方法(如果已定义),或者引发HttpResponseNotAllowed(如果不是)。


所以我以为如果我在调度中返回一个错误的回复,那么不应该执行post方法,为什么要被执行?我在这里做错了什么?

解决方案

由于您没有提供调度方法代码,只会被猜测。
我的2美分是你在某个时候调用MasterClass的超级,这将调用APIView调度,这将调用你的POST。


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?

解决方案

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.

这篇关于Django - DRF - 调度方法流程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆