首页 > 编程语言 >drf源码剖析----认证

drf源码剖析----认证

时间:2024-03-08 10:56:29浏览次数:19  
标签:self request auth ---- 源码 user kwargs def drf

点击查看代码
class Request:

    def __init__(self, request, authenticators=None):
        self._request = request
        self.authenticators = authenticators or ()

    @property
    def user(self):
     # 类Request()中没有'_user',访问self._authenticate()
        if not hasattr(self, '_user'):
            with wrap_attributeerrors():
                self._authenticate()
        return self._user

    def _authenticate(self):
        # 依次执行认证类对象的authenticate()方法,即类MyAuthentication()的方法
        for authenticator in self.authenticators:
            try:
                user_auth_tuple = authenticator.authenticate(self)
            except exceptions.APIException:
                self._not_authenticated()
                raise

            if user_auth_tuple is not None:
                self._authenticator = authenticator
                self.user, self.auth = user_auth_tuple
                return

        self._not_authenticated()

    def _not_authenticated(self):
        self._authenticator = None

        if api_settings.UNAUTHENTICATED_USER:
            self.user = api_settings.UNAUTHENTICATED_USER()
        else:
            self.user = None

        if api_settings.UNAUTHENTICATED_TOKEN:
            self.auth = api_settings.UNAUTHENTICATED_TOKEN()
        else:
            self.auth = None
点击查看代码
class APIView(View):
    authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES

    def perform_authentication(self, request):
        # 类APIView()中没有user属性和方法,到类View()中找
        request.user

    def initial(self, request, *args, **kwargs):
        self.perform_authentication(request)
        self.check_permissions(request)
        self.check_throttles(request)

    def get_authenticators(self):
       # 优先读取UserView()中的authentication_classes,没有则读取APIView()中的, 
       # 并返回实例化对象
        return [auth() for auth in self.authentication_classes]
    
    def initialize_request(self, request, *args, **kwargs):
        return Request(
            request,
            parsers=self.get_parsers(),
            authenticators=self.get_authenticators(),
            negotiator=self.get_content_negotiator(),
            parser_context=parser_context
        )

    def dispatch(self, request, *args, **kwargs):
        self.args = args
        self.kwargs = kwargs
        # django中的request和认证组件 放入initialize_request()中封装 
        request = self.initialize_request(request, *args, **kwargs)
        self.request = request
        self.headers = self.default_response_headers  # deprecate?

        try:
           # drf的request放入self.initial()中封装
            self.initial(request, *args, **kwargs)
            if request.method.lower() in self.http_method_names:
                handler = getattr(self, request.method.lower(),
                                  self.http_method_not_allowed)
            else:
                handler = self.http_method_not_allowed

            response = handler(request, *args, **kwargs)

        except Exception as exc:
            response = self.handle_exception(exc)

        self.response = self.finalize_response(request, response, *args, **kwargs)
        return self.response
点击查看代码
class UserView(APIView):
    authentication_classes = [类1, 类2, 类3]

    def get(self, request):
        print(request.user, request.auth)
        return Response('UserView')

#  请求到来时
#  obj = UserView()
#  obj.dispatch()
#  类UserView()中,没有dispatch()方法,到父类APIView()中找
点击查看代码
class MyAuthentication(BaseAuthentication):

    def authenticate(self, request):
        token = request.query_params.get('token')
        if token:
            return'zyb', token
        raise AuthenticationFailed({'code': 200, 'error': '认证失败'})

标签:self,request,auth,----,源码,user,kwargs,def,drf
From: https://www.cnblogs.com/only-you-zta/p/18059126

相关文章

  • MySQL Server架构概述
    推荐:SQL语句执行顺序相关问题。MySQLServer架构分层概述MySQLServer架构可抽象为3层。连接层:验证用户名密码,认证成功后,获取当前账号的权限并缓存,并分配TCP连接池和线程池资源。处理层:实现核心的处理功能。存储层:将处理后的数据高性能安全的写入磁盘,或从磁盘中正确的读取......
  • 01_单例模式
    单例模式是一种常见的设计模式,用于确保一个类只有一个实例,并提供一个全局访问点。在单例模式中,类会提供一个静态方法来获取其唯一实例,如果该实例不存在则会创建一个新实例,否则返回已有的实例。publicsealedclassCounter{publicCounter(){......
  • Go和TinyGo
    Go和TinyGo是两种不同的Go语言编译器,它们之间有以下几点区别:目标平台:Go:Go语言编译器主要面向通用计算机平台,如Windows、Linux、macOS等。TinyGo:TinyGo专注于支持嵌入式系统和物联网设备等资源受限的平台,如微控制器、嵌入式设备、WebAssembly等。性能:Go:Go编译器生成的......
  • @ConfigurationProperties(prefix = GatewayProperties.PREFIX)
    在Spring Boot中,@ConfigurationProperties注解用于将配置文件(如application.properties或application.yml)中的属性绑定到一个Java Bean上。通过指定prefix属性,可以选择性地绑定配置文件中特定前缀下的属性到Bean的字段上。这种方式简化了配置管理,使得配置数据的组织和使用更加灵......
  • @Indexed
    假设你有一个服务类,你希望Spring在启动时能够快速地识别并注册它:importorg.springframework.stereotype.Indexed;importorg.springframework.stereotype.Service;@Indexed@ServicepublicclassMyService{   //类的实现}在这个例子中,@Service注解标记这个类为一个服务组......
  • Flink CDC 写 StarRocks
    Flink版本:1.17.1CDC版本:2.3.0StarRocks版本:2.5.8前言最近需要实时同步几个Mysql表到StarRocks,薅出之前写的Demo代码,简单改造了一下,加了个配置文件,可以通过修改配置文件指定source、sink表,这样就不用讲表名什么的写死到代码里面。再利用flinksession模式,把一堆任......
  • 清理挖矿程序的脚本
    systemctldisablemyservice.servicesystemctlstopmyservice.servicesystemctlstatusmyservice.servicerm-fr/usr/lib/systemd/system/myservice.servicerm-fr/root/.cfgrm-fr/usr/bin/mslogrm-fr/usr/bin/playersed-i/disown/d/var/spool/cron/root......
  • 新建数据库报错亦或者root 账号无法显示所有数据库
    NavicatPremium创建数据库报1044-Accessdeniedforuser'root'@'%'todatabase1查询权限SELECThost,user,Grant_priv,Super_privFROMmysql.user; 2、修改权限UPDATEmysql.userSETGrant_priv='Y',Super_priv='Y'WHEREUse......
  • el-date-picker type=datetime时设置默认时间
    vue2设置默认时间<el-date-pickerv-model="value3"type="datetime"placeholder="选择日期时间"default-time="12:00:00"></el-date-picker>vue3设置默认时间<el-date-pickerv-model=&q......
  • React设计原理解密及核心源码解读
    一、React基础回顾1、react介绍React是一个用于构建用户界面的JavaScript库,它只负责应用的视图层,帮助开发人员构建快速且交互式的web应用程序。React使用组件的方式构建用户界面。2、JSX语法回顾在React中使用JSX语法描述用户界面,它是一种JavaScript语法扩展......