认证组件

发生位置

APIview 类种的 dispatch 方法执行到 initial 方法 进行 认证组件认证

源码位置

rest_framework.authentication

 源码内部需要了解的

# 用户用户自定义的重写继承类
class BaseAuthentication(object):
...
# 自定义重写的认证方法
def authenticate(self, request):... # 以下4种为自带 认证 # 基于用户名和密码的认证
class BasicAuthentication(BaseAuthentication):... # 基于 session 的认证
class SessionAuthentication(BaseAuthentication):... # 基于 token 的认证
class TokenAuthentication(BaseAuthentication):... # 基于远端服务的认证
class RemoteUserAuthentication(BaseAuthentication):...

自定义认证函数

from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from api.models import * class YTAuth(BaseAuthentication):
def authenticate(self, request):
token = request.query_params.get('token')
obj = UserAuthToken.objects.filter(token=token).first()
if not obj:
return AuthenticationFailed({'code': 1001, 'erroe': '认证失败'})
return (obj.user.username, obj)
  # 返回的必须是元组 然后元组的里面含有两个值 并且对应的取值是rquest.user(user对象),和reques.auth(token对象)

 视图级别认证

class CommentViewSet(ModelViewSet):

    queryset = models.Comment.objects.all()
serializer_class = app01_serializers.CommentSerializer
authentication_classes = [YTAuth, ]

 全局认证

# 在settings.py中配置
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": ["app01.utils.YTAuth", ]
}

权限组件

发生位置

APIview 类种的 dispatch 方法执行到 initial 方法 进行 认证组件执行后,进行权限组件认证

源码位置

rest_framework.permissions

权限组件内部需要了解的

# 自定义重写的类
class BasePermission(object):
...
# 自定义重写的方法
def has_permission(self, request, view): ... # AllowAny 允许所有用户
class AllowAny(BasePermission):... # IsAuthenticated 仅通过认证的用户
class IsAuthenticated(BasePermission):... # IsAdminUser 仅管理员用户
class IsAdminUser(BasePermission):... # IsAuthenticatedOrReadOnly 认证的用户可以完全操作,否则只能get读取
class IsAuthenticatedOrReadOnly(BasePermission):...

 自定义权限组件

from rest_framework.permissions import BasePermission

class MyPermission(BasePermission):
message = 'VIP用户才能访问' def has_permission(self, request, view):
# 认证判断已经提供了request.user
if request.user and request.user.type == 2:
return True
else:
return False

 视图级别使用自定义权限组件

class CommentViewSet(ModelViewSet):
queryset = models.Comment.objects.all()
serializer_class = app01_serializers.CommentSerializer
authentication_classes = [YTAuth, ]
permission_classes = [YTPermission, ]

 全局级别使用自定义权限组件

# 在settings.py中设置rest framework相关配置项
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": ["app01.utils.YTAuth", ],
"DEFAULT_PERMISSION_CLASSES": ["app01.utils.YTPermission", ]
}

频率限制

发生位置

APIview 类种的 dispatch 方法执行到 initial 方法 进行 认证组件执行,权限组件认证后 ,进行频率组件的认证

源码位置

rest_framework.throttling

权限组件内部需要了解的

# 需要自定义重写的类
class BaseThrottle(object):
...
# 自定义频率的逻辑实现方法
def allow_request(self, request, view):
...
# 自定义 限制后逻辑实现方法
def wait(self):
... # 内置的频率控制组件 常用的是这个
class SimpleRateThrottle(BaseThrottle): ... # 其他都不怎么用
class AnonRateThrottle(SimpleRateThrottle): ... # 其他都不怎么用
class UserRateThrottle(SimpleRateThrottle): # 其他都不怎么用
class ScopedRateThrottle(SimpleRateThrottle):

自定义频率组件

import time

VISIT_RECORD = {}
class YTThrottle(object): # 直接继承 object 就可以了
def __init__(self):
self.history = None
def allow_request(self, request, view):
"""
自定义频率限制60秒内只能访问三次
"""
# 获取用户IP
ip = request.META.get("REMOTE_ADDR")
timestamp = time.time()
if ip not in VISIT_RECORD:
VISIT_RECORD[ip] = [timestamp, ]
return True
history = VISIT_RECORD[ip]
self.history = history
history.insert(0, timestamp)
while history and history[-1] < timestamp - 60:
history.pop()
if len(history) > 3:
return False
else:
return True
def wait(self):
"""
限制时间还剩多少
"""
timestamp = time.time()
return 60 - (timestamp - self.history[-1])

 视图级别使用自定义频率组件

class CommentViewSet(ModelViewSet):

    queryset = models.Comment.objects.all()
serializer_class = app01_serializers.CommentSerializer
throttle_classes = [YTThrottle, ]

 全局级别使用自定义频率组件

# 在settings.py中设置rest framework相关配置项
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": ["app01.utils.YTAuth", ],
"DEFAULT_PERMISSION_CLASSES": ["app01.utils.YTPermission", ]
"DEFAULT_THROTTLE_CLASSES": ["app01.utils.YTThrottle", ]
}

ps:

  使用内置 SimpleRateThrottle 频率控制组件

from rest_framework.throttling import SimpleRateThrottle

class VisitThrottle(SimpleRateThrottle):

    scope = "xxx"

    def get_cache_key(self, request, view):
return self.get_ident(request)

全局使用 

# 在settings.py中设置rest framework相关配置项
REST_FRAMEWORK = {
  ...
  "DEFAULT_THROTTLE_RATES": {
"xxx": "5/m", # 每分钟5次最多
}
}

rest framework 认证 权限 频率的更多相关文章

  1. restful知识点之三restframework认证-->权限-->频率

    认证.权限.频率是层层递进的关系 权限业务时认证+权限 频率业务时:认证+权限+频率 局部认证方式 from django.conf.urls import url,include from djan ...

  2. 实战-DRF快速写接口(认证权限频率)

    实战-DRF快速写接口 开发环境 Python3.6 Pycharm专业版2021.2.3 Sqlite3 Django 2.2 djangorestframework3.13 测试工具 Postma ...

  3. Django REST framework认证权限和限制 源码分析

    1.首先 我们进入这个initial()里面看下他内部是怎么实现的. 2.我们进入里面看到他实现了3个方法,一个认证,权限频率 3.我们首先看下认证组件发生了什么 权限: 啥都没返回,self.per ...

  4. Django REST framework认证权限和限制和频率

    认证.权限和限制 身份验证是将传入请求与一组标识凭据(例如请求来自的用户或其签名的令牌)相关联的机制.然后 权限 和 限制 组件决定是否拒绝这个请求. 简单来说就是: 认证确定了你是谁 权限确定你能不 ...

  5. Django REST Framework 认证 - 权限 - 限制

    一. 认证 (你是谁?) REST framework 提供了一些开箱即用的身份验证方案,并且还允许你实现自定义方案. 自定义Token认证 第一步 : 建表>>>> 定义一个 ...

  6. 8) drf 三大认证 认证 权限 频率

    一.三大认证功能分析 1)APIView的 dispath(self, request, *args, **kwargs) 2)dispath方法内 self.initial(request, *ar ...

  7. DRF-认证 权限 频率组件

    补充 1 认证 权限 频率组件原理基本相同 2 认证相关: session cookie token 认证相关的  这里用token token 1 有时间限制,超时则失效 2 每次登录更换一个tok ...

  8. DRF-认证权限频率

    目录 DRF-认证权限频率 认证 登录接口 认证 权限 作用 使用 频率 作用 使用 认证权限频率+五个接口 模型 视图 序列化器 认证权限频率类 配置文件 路由 DRF-认证权限频率 前后端混合开发 ...

  9. Django Rest Framework(认证、权限、限制访问频率)

    阅读原文Django Rest Framework(认证.权限.限制访问频率) django_rest_framework doc django_redis cache doc

随机推荐

  1. 解决Centos7 yum 出现could not retrieve mirrorlist 错误

    刚通过VMware12安装了centos7.x后,使用ip addr查看centos局域网的ip发现没有,使用yum安装一些工具包时也出现报错: Loaded plugins: fastestmirr ...

  2. centos6.3部署配置LVS主从

    LVS是Linux Virtual Server的简写,即Linux虚拟服务器,是一个虚拟的服务器集群系统.这个项目在1998年5月由章文嵩博士成立,是中国国内最早出现的自由软件项目之一.它的官方网址 ...

  3. iOS-----------关于UDID

    最近看友盟的SDK更新日志:(设备系统的正常升级不会改变OpenUDID) Apple公司于2013年5月1日开始,拒绝采集UDID的App上架App Store. 为适应Apple公司的这一政策,2 ...

  4. 美团技术沙龙01 - 58到家服务的订单调度&数据分析技术

    1. 2015.4.15 到家服务的订单调度&数据分析技术 58到家· 黄海斌 @xemoaya 2.agenda • 58到家介绍 • 订单管理系统介绍 • 数据分析技术的应用 3.2015 ...

  5. 牛客网:java入门实现遍历目录

    项目介绍 遍历目录是操作文件时的一个常见需求.比如写一个程序,需要找到并处理指定目录下的所有JS文件时,就需要遍历整个目录.该项目教会你如何使用流式编程和lambda表达式,帮助你进一步熟悉java8 ...

  6. 解决jest处理es模块

    解决jest处理es模块 问题场景 项目使用jest进行测试时, 当引入外部库是es模块时, jest无法处理导致报错. Test suite failed to run Jest encounter ...

  7. web.xml文件介绍

    每个javaEE工程中都有web.xml文件,那么它的作用是什么呢?它是每个web.xml工程都必须的吗? 一个web中可以没有web.xml文件,也就是说,web.xml文件并不是web工程必须的. ...

  8. 【Eclipse】springMVC介绍与配置

    SpringMCV介绍: Spring MVC是一种基于Java的实现了MVC设计模式的请求驱动类型的轻量级Web框架,即使用了MVC架构模式的思想,将web层进行职责解耦,基于请求驱动的,也就是使用 ...

  9. mysql 将一个表中的数据复制到另一个表中,sql语句

    1.表结构相同的表,且在同一数据库(如,table1,table2) Sql :insert into table1 select * from table2 (完全复制) insert into t ...

  10. python文件上传

    1.前端代码 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UT ...