django rest framework用户认证


  • 进入rest framework的Apiview

      1. @classmethod
      2. def as_view(cls, **initkwargs):
      3. """
      4. Store the original class on the view function.
      5.  
      6. This allows us to discover information about the view when we do URL
      7. reverse lookups. Used for breadcrumb generation.
      8. """
      9. if isinstance(getattr(cls, 'queryset', None), models.query.QuerySet):
      10. def force_evaluation():
      11. raise RuntimeError(
      12. 'Do not evaluate the `.queryset` attribute directly, '
      13. 'as the result will be cached and reused between requests. '
      14. 'Use `.all()` or call `.get_queryset()` instead.'
      15. )
      16. cls.queryset._fetch_all = force_evaluation
      17.  
      18. view = super().as_view(**initkwargs)
      19. view.cls = cls
      20. view.initkwargs = initkwargs
      21.  
      22. # Note: session based authentication is explicitly CSRF validated,
      23. # all other authentication is CSRF exempt.
      24. return csrf_exempt(view)

      django的类视图是调用内部的as_view方法来实现CBV,在第18行调用了父类的as_view,父类的as_view调用了dispatch方法,这里在ApiView自定义了dispatch


      1. def dispatch(self, request, *args, **kwargs):
      2. """
      3. `.dispatch()` is pretty much the same as Django's regular dispatch,
      4. but with extra hooks for startup, finalize, and exception handling.
      5. """
      6. self.args = args
      7. self.kwargs = kwargs
      8. request = self.initialize_request(request, *args, **kwargs)
      9. self.request = request
      10. self.headers = self.default_response_headers # deprecate?
      11.  
      12. try:
      13. self.initial(request, *args, **kwargs)
      14.  
      15. # Get the appropriate handler method
      16. if request.method.lower() in self.http_method_names:
      17. handler = getattr(self, request.method.lower(),
      18. self.http_method_not_allowed)
      19. else:
      20. handler = self.http_method_not_allowed
      21.  
      22. response = handler(request, *args, **kwargs)
      23.  
      24. except Exception as exc:
      25. response = self.handle_exception(exc)
      26.  
      27. self.response = self.finalize_response(request, response, *args, **kwargs)
      28. return self.response

      和django的dispatch类似,第8,9行对request进行了封装

      1. def initialize_request(self, request, *args, **kwargs):
      2. """
      3. Returns the initial request object.
      4. """
      5. parser_context = self.get_parser_context(request)
      6.  
      7. return Request(
      8. request,
      9. parsers=self.get_parsers(),
      10. authenticators=self.get_authenticators(),
      11. negotiator=self.get_content_negotiator(),
      12. parser_context=parser_context
      13. )

      封装函数内部返回的是Request对象

      1. class Request:
      2. """
      3. Wrapper allowing to enhance a standard `HttpRequest` instance.
      4.  
      5. Kwargs:
      6. - request(HttpRequest). The original request instance.
      7. - parsers_classes(list/tuple). The parsers to use for parsing the
      8. request content.
      9. - authentication_classes(list/tuple). The authentications used to try
      10. authenticating the request's user.
      11. """
      12.  
      13. def __init__(self, request, parsers=None, authenticators=None,
      14. negotiator=None, parser_context=None):
      15. assert isinstance(request, HttpRequest), (
      16. 'The `request` argument must be an instance of '
      17. '`django.http.HttpRequest`, not `{}.{}`.'
      18. .format(request.__class__.__module__, request.__class__.__name__)
      19. )
      20.  
      21. self._request = request
      22. self.parsers = parsers or ()
      23. self.authenticators = authenticators or ()
      24. self.negotiator = negotiator or self._default_negotiator()
      25. self.parser_context = parser_context
      26. self._data = Empty
      27. self._files = Empty
      28. self._full_data = Empty
      29. self._content_type = Empty
      30. self._stream = Empty
      31.  
      32. if self.parser_context is None:
      33. self.parser_context = {}
      34. self.parser_context['request'] = self
      35. self.parser_context['encoding'] = request.encoding or settings.DEFAULT_CHARSET
      36.  
      37. force_user = getattr(request, '_force_auth_user', None)
      38. force_token = getattr(request, '_force_auth_token', None)
      39. if force_user is not None or force_token is not None:
      40. forced_auth = ForcedAuthentication(force_user, force_token)
      41. self.authenticators = (forced_auth,)

      Request对象的初始化函数,它将原生django的request对象赋值给self._request,所以在ApiView视图中想使用原生的request要用request._request来使用

    • 查看self.authenticators
    • self.authenticators等于传进来的authenticators
    • 在ApiView内部定义了get_authenticators方法,它会被authenticators来接受
      1. def get_authenticators(self):
      2. """
      3. Instantiates and returns the list of authenticators that this view can use.
      4. """
      5. return [auth() for auth in self.authentication_classes]

      这个方法回去self.authentication_classes里面找定义好的对象再将其实例化

    • 定义自定义验证类
      1. from rest_framework.views import APIView
      2. from django.http import HttpResponse
      3. from rest_framework.authentication import BaseAuthentication
      4. from rest_framework.exceptions import AuthenticationFailed
      5.  
      6. class MyAuthentication(BaseAuthentication):
      7. def authenticate(self, request):
      8. if not request._request.GET.get('name'):
      9. raise AuthenticationFailed
      10. return ('user', None)
      11.  
      12. def authenticate_header(self, request):
      13. pass
      14.  
      15. class MyView(APIView):
      16. authentication_classes = [MyAuthentication]
      17.  
      18. def get(self, request):
           user = request.user
      19. return HttpResponse(user)

      验证类继承BaseAuthentication(不继承也可以,但都要实现authenticate)方法,在authenticate里面实现用户的认证,最后返回一个元祖,第一个元素为user对象,该对象被request.user接受, 第二个元素会被request.auth捕捉

    • 效果

django rest framework用户认证的更多相关文章

  1. Django Rest framework 之 认证

    django rest framework 官网 django rest framework 之 认证(一) django rest framework 之 权限(二) django rest fra ...

  2. Django 中的用户认证

    Django 自带一个用户认证系统,这个系统处理用户帐户.组.权限和基于 cookie 的 会话.本文说明这个系统是如何工作的. 概览 认证系统由以下部分组成: 用户 权限:控制用户进否可以执行某项任 ...

  3. Django rest framework 的认证流程(源码分析)

    一.基本流程举例: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^users/', views.HostView.as_view() ...

  4. Django Rest Framework用户访问频率限制

    一. REST framework的请求生命周期 基于rest-framework的请求处理,与常规的url配置不同,通常一个django的url请求对应一个视图函数,在使用rest-framewor ...

  5. Django组件之用户认证组件

    一.auth模块 from django.contrib import auth django.contrib.auth中提供了许多方法,这里主要介绍其中的三个: 1.1 .authenticate( ...

  6. Django Rest Framework之认证

    代码基本结构 url.py: from django.conf.urls import url, include from web.views.s1_api import TestView urlpa ...

  7. 使用django实现自定义用户认证

    参考资料:https://docs.djangoproject.com/en/1.10/topics/auth/customizing/    直接拉到最后看栗子啦 django自定义用户认证(使用自 ...

  8. 09 Django组件之用户认证组件

    没有学习Django认证组件之前使用装饰器方法 from django.shortcuts import render, HttpResponse, redirect from app01.MyFor ...

  9. Django组件之用户认证

    auth模块 1 from django.contrib import auth django.contrib.auth中提供了许多方法,这里主要介绍其中的三个: 1.1 .authenticate( ...

随机推荐

  1. frida(hook工具)的环境搭建

    一.简介 frida 是一款基于 python+javascript 的 hook 框架,可运行在 android.ios.linux.win等各个平台,主要使用的动态二进制插桩技术. Frida官网 ...

  2. DS01-线性表

    0.PTA得分截图 1.本周内容总结 1.1总结线性表内容 顺序表结构体定义 typedef struct LNode *List struct LNode { ElementType Data[MA ...

  3. 视觉目标跟踪算法——SRDCF算法解读

    首先看下MD大神2015年ICCV论文:Martin Danelljan, Gustav Häger, Fahad Khan, Michael Felsberg. "Learning Spa ...

  4. 1. python跨目录调用模块

    快速镜像安装第三方库 :  pip install -i https://pypi.tuna.tsinghua.edu.cn/simple numpy (三方库名字) 同目录下,我们可以直接调用模块, ...

  5. requests模块使用一

    1.安装与简介 Urllib和requests模块是python中发起http请求最常见的模块,但是requests模块使用更加方便简单. pip install requests 2.GET请求 2 ...

  6. Mass Spectrometry-Compatible Subcellular Fractionation for Proteomics 质谱兼容的蛋白质组学的亚细胞分离(解读人:王茹凯)

    文献名:Mass Spectrometry-Compatible Subcellular Fractionation for Proteomics(质谱兼容的蛋白质组学的亚细胞分离) 期刊名:Jpor ...

  7. IntelliJ IDEA 2018.1.4 x64安装创建maven项目等

    Intellij IDEA 一:介绍 Jetbrains公司https://www.jetbrains.com/idea/ 1.1版本 Ultimate最终[收费] 网络,移动和企业开发 Web, m ...

  8. 补充JavaScript

    1 JavaScript概述 1.1 ECMAScript和Javascript的关系 1996年11月,JavaScript的创造者--Netscape公司,决定将JavaScript提交给国际标准 ...

  9. 题解 P5835 【 USACO19DEC Meetings S】

    前言 这道题目是道好题,想通了之后就可以把轻松这道题做出来. 正文 结论 先把一个结论写出来. 无论所有奶牛怎么走,它们的体重从左往右组成的序列是不会发生改变的. 这个结论简单地说明一下. 首先我们可 ...

  10. word2vec 和 glove 模型的区别

    2019-09-09 15:36:13 问题描述:word2vec 和 glove 这两个生成 word embedding 的算法有什么区别. 问题求解: GloVe (global vectors ...