比如有下面一个View,比较简单:
class UsersView(View):
def get(self,request):
......
这个GET方法会接受一个参数id
,也就是用户的ID,理想的状态是只要进入get方法内,那么这个用户就是存在的,否则就直接抛404或者其他。
但现在的做法是在view里面做判断用户是否存在,然后再做不同的操作。
class UsersView(View):
authentication_classes = ....
permission_classes = ....
serializer_class = ....
不知道rest
里面有没有这种方法,可以在进入View里面之前就可以做参数的验证,而不用在View里面。
ringa_lee2017-04-18 10:32:49
Rest's view has authentication_classes set up. You can perform corresponding authentication before entering the view function. You can write a customized authentication class, inherit the authentication.BaseAuthentication class and implement the authentication(self, request) method. In this method, you need to Logical judgment, return corresponding error information, etc.
But it is mainly used for authentication of the current requesting user. For example, it is normal to write it in the view to determine whether the ID exists. If multiple views need it, you can write a decorator.