search

Home  >  Q&A  >  body text

python - django-rest-framework如何实现对view参数进行认证的

比如有下面一个View,比较简单:

class UsersView(View):
   def get(self,request):
      ......

这个GET方法会接受一个参数id,也就是用户的ID,理想的状态是只要进入get方法内,那么这个用户就是存在的,否则就直接抛404或者其他。

但现在的做法是在view里面做判断用户是否存在,然后再做不同的操作。

Q

class UsersView(View):
    authentication_classes = ....
    permission_classes = ....
    serializer_class = ....

不知道rest里面有没有这种方法,可以在进入View里面之前就可以做参数的验证,而不用在View里面。

PHP中文网PHP中文网2786 days ago532

reply all(2)I'll reply

  • 黄舟

    黄舟2017-04-18 10:32:49

    Resources that cannot be requested will automatically throw a 404 error

    reply
    0
  • ringa_lee

    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.

    reply
    0
  • Cancelreply