Django - DRF - 调度方法流 [英] Django - DRF - dispatch method flow
问题描述
我正在使用 DRF 构建 API,并且我使用了一个主类对基于类的视图进行了一些验证:
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
# ...
验证失败,至少有一个,但正在执行数据库事务,我实际上从 dispatch
方法得到了一条错误消息的响应,但是 post
方法是在 dispatch
之前执行,我使用断点来查看流程,这是进入 post
方法然后进入 dispatch
方法,就像他们是分开的线程.
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.
来自文档:
as_view 入口点创建类的实例并调用它的 dispatch() 方法.dispatch 查看请求以确定是否是 GET、POST 等,并将请求中继到匹配的如果定义了方法,则为方法,否则引发 HttpResponseNotAllowed.
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.
所以我想如果我在dispatch中返回一个错误的响应,post方法不应该被执行,为什么它会被执行?我在这里做错了什么?
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?
推荐答案
由于您没有提供调度方法代码,因此只能是猜测.我的 2 美分是你在某个时候调用 MasterClass 的 super,它会调用 APIView 调度,它会调用你的 POST.
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屋!