为了方便接下来的学习,我们创建一个新的子应用 four

python manage.py startapp four

因为接下来的功能中需要使用到登陆功能,所以我们使用django内置admin站点并创建一个管理员.

python manage.py createsuperuser

创建管理员以后,访问admin站点,先修改站点的语言配置

settings.py

访问admin 站点效果:

1. 认证Authentication

rest_framework.settings里面有默认的全局配置,不过我们可以在自己项目的setting.py文件中进行配置覆盖

可以在配置文件中(项目中的setting.py)配置全局默认的认证方案

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication', # session认证
'rest_framework.authentication.BasicAuthentication', # 基本认证
)
}

也可以在每个视图中通过设置authentication_classess属性来设置(局部)

from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.views import APIView

class ExampleView(APIView):
# 类属性
authentication_classes = [SessionAuthentication, BasicAuthentication]
...

认证失败会有两种可能的返回值:

  • 401 Unauthorized 未认证

  • 403 Permission Denied 权限被禁止

2. 权限Permissions

权限控制可以限制用户对于视图的访问和对于具体数据对象的访问。

  • 在执行视图的dispatch()方法前,会先进行视图访问权限的判断

  • 在通过get_object()获取具体对象时,会进行模型对象访问权限的判断

使用

可以在配置文件(项目中的setting.py)中全局设置默认的权限管理类,如

REST_FRAMEWORK = {
.... 'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}

如果未指明,则采用如下(rest_framework.settings)默认配置

'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
)

也可以在具体的视图中通过permission_classes属性来设置(局部),如

from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView

class ExampleView(APIView):
permission_classes = (IsAuthenticated,)
...

提供的权限

  • AllowAny 允许所有用户

  • IsAuthenticated 仅通过认证的用户

  • IsAdminUser 仅管理员用户

  • IsAuthenticatedOrReadOnly 已经登陆认证的用户可以对数据进行增删改操作,没有登陆认证的只能查看数据。

举例

from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import AllowAny,IsAdminUser,IsAuthenticated class ExampleAPIView(APIView):
authentication_classes = [SessionAuthentication]
permission_classes = [IsAuthenticated]
def get(self,request):
print( type( request.user ) )
return Response({"message":"ok"})

自定义权限

如需自定义权限,需继承rest_framework.permissions.BasePermission父类,并实现以下两个任何一个方法或全部

  • .has_permission(self, request, view)

    是否可以访问视图, view表示当前视图对象

  • .has_object_permission(self, request, view, obj)

    是否可以访问数据对象, view表示当前视图, obj为数据对象

例如:

在当前子应用下,创建一个权限文件permissions.py中声明自定义权限类:

from rest_framework.permissions import BasePermission

class IsXiaoMingPermission(BasePermission):
def has_permission(self, request, view):
if( request.user.username == "xiaoming" ):
return True
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import AllowAny,IsAdminUser,IsAuthenticated from .permissions import IsXiaoMingAuthentication class ExampleAPIView(APIView):
authentication_classes = [SessionAuthentication]
permission_classes = [IsXiaoMingAuthentication]
def get(self,request):
print( type( request.user ) )
return Response({"message":"ok"})

3. 限流Throttling

可以对接口访问的频次进行限制,以减轻服务器压力。

一般用于付费购买次数,投票等场景使用.

使用

可以在配置文件中,使用DEFAULT_THROTTLE_CLASSESDEFAULT_THROTTLE_RATES进行全局配置,

REST_FRAMEWORK = {
# 限流[全局]
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttling.AnonRateThrottle', # 匿名用户,游客
'rest_framework.throttling.UserRateThrottle' # 已经经过认证的用户
),
'DEFAULT_THROTTLE_RATES': {
'anon': '300/minute',
'user': '1000/minute'
},
}

DEFAULT_THROTTLE_RATES 可以使用 second, minute, hourday来指明周期。

也可以在具体视图中通过throttle_classess属性来配置,如

from rest_framework.throttling import UserRateThrottle
from rest_framework.views import APIView

class ExampleView(APIView):
throttle_classes = (UserRateThrottle,)
...

可选限流类

1) AnonRateThrottle

限制所有匿名未认证用户,使用IP区分用户。

使用DEFAULT_THROTTLE_RATES['anon'] 来设置频次

2)UserRateThrottle

限制认证用户,使用User id 来区分。

使用DEFAULT_THROTTLE_RATES['user'] 来设置频次

3)ScopedRateThrottle

限制用户对于每个视图的访问频次,使用ip或user id。

例如:

class ContactListView(APIView):
throttle_scope = 'contacts'
...

class ContactDetailView(APIView):
throttle_scope = 'contacts'
...

class UploadView(APIView):
throttle_scope = 'uploads'
...
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttling.ScopedRateThrottle',
),
'DEFAULT_THROTTLE_RATES': {
'contacts': '1000/day',
'uploads': '20/day'
}
}

实例

全局配置中设置访问频率

 'DEFAULT_THROTTLE_RATES': {
'anon': '3/minute',
'user': '10/minute'
} from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.generics import RetrieveAPIView
from rest_framework.throttling import UserRateThrottle

class StudentAPIView(RetrieveAPIView):
queryset = Student.objects.all()
serializer_class = StudentSerializer
authentication_classes = [SessionAuthentication]
permission_classes = [IsAuthenticated]
throttle_classes = (UserRateThrottle,)

drf06 认证Authentication 权限Permissions 限流Throttling的更多相关文章

  1. drf 认证、权限、限流、过滤、排序、分页器

    认证Authentication 准备工作:(需要结合权限用) 1. 需要使用到登陆功能,所以我们使用django内置admin站点并创建一个管理员. python manage.py creates ...

  2. 2. DRF 认证、权限、限流、分页、过滤、序列 化

    2.1 user/urls.py   ModelViewSet注册路由三部曲 from django.urls import include, path from user import views ...

  3. drf认证、权限、限流

    认证Authentication(5星) 认证逻辑及编写步骤 逻辑 认证类:用来校验用户是否登录,如果登录了,继续往下走,如果没有登录,直接返回 编写步骤 -第一步:写一个类,继承BaseAuthen ...

  4. 45.限流Throttling及源码解析

    什么是限流? 限流类似于权限机制,它也决定是否接受当前请求,用于控制客户端在某段时间内允许向API发出请求的次数,也就是频率 假设有客户端(比如爬虫程序)短时间发起大量请求,超过了服务器能够处理的能力 ...

  5. django-rest-framework-源码解析004-三大验证(认证/权限/限流)

    三大验证模块概述 在DRF的APIView重写的dispatch方法中,  self.initial(request, *args, **kwargs) 这句话就是执行三大验证的逻辑, 点进去可以看到 ...

  6. day1(ModelViewSet序列化限流排序)

    1.DRF初始化 1.认证 2.权限 3.限流 4.序列化 5.分页 6.版本  7.过滤 8.排序 1.1安装DjangoRestFramework pip install djangoresfra ...

  7. 三 drf 认证,权限,限流,过滤,排序,分页,异常处理,接口文档,集xadmin的使用

    因为接下来的功能中需要使用到登陆功能,所以我们使用django内置admin站点并创建一个管理员. python manage.py createsuperuser 创建管理员以后,访问admin站点 ...

  8. day74:drf:drf其他功能:认证/权限/限流/过滤/排序/分页/异常处理&自动生成接口文档

    目录 1.django-admin 2.认证:Authentication 3.权限:Permissions 4.限流:Throttling 5.过滤:Filtering 6.排序:OrderingF ...

  9. WCF Throttling 限流的三道闸口

    WCF Throttling 限流的三道闸口 一.WCF Throttling  流量限制简介 我们期望WCF服务端能够处理尽可能多的并发请求,但是资源是有限的,服务不可能同时处理无限多的并发请求,如 ...

随机推荐

  1. C++ Sleep Function 使用方法 Sleep(-1)

    <span style="font-size:18px;">//==================================================== ...

  2. Python3基础(八) 模块

    在程序中定义函数可以实现代码重用.但当你的代码逐渐变得庞大时,你可能想要把它分割成几个文件,以便能够更简单地维护.同时,你希望在一个文件中写的代码能够被其他文件所重用,这时我们应该使用模块(modul ...

  3. Eclipse下单个文件中文乱码问题

    有时候用eclipse打开单个文件,会出现中文乱码问题. 这时可以点菜单栏 Edit -> Set Encoding,Other:UTF-8,通常可以解决问题.

  4. LaTeX 在线编辑器(LaTeX online editors)

    eqneditor:有强大的几乎所有常用的数学符号对应的图标形式,便于快速完成latex公式编辑且易于粘贴拷贝. 此外,更为重要的一点是,随着编辑窗口内公式的编辑,会在页面的底部,自动生成其对应的 h ...

  5. [bzoj5404]party

    https://zybuluo.com/ysner/note/1240918 题面 这题面不好概括啊 解析 \(5pts\)算法 既然\(q=0\),打上文件输入输出即可. 当然不开够空间且不特判的小 ...

  6. P3399 丝绸之路(线性二维dp)

    P3399 丝绸之路 题目背景 张骞于公元前138年曾历尽艰险出使过西域.加强了汉朝与西域各国的友好往来.从那以后,一队队骆驼商队在这漫长的商贸大道上行进,他们越过崇山峻岭,将中国的先进技术带向中亚. ...

  7. Java使用Player播放mp3

    大家平时闲了都会听听歌,散散心,于是很多人就问,在Java里边如何播放歌曲呢,唉,别说,在Java里边还真能歌曲,下面我为大家揭晓. 我们都知道Java里边做什么都需要对应的jar包,首先贴上mave ...

  8. php从数据库读取中文显示问号??的解决办法

    出错原因:1.数据库编码格式不对 2.PHP编码格式不对 3.浏览器编码格式不对 上面三者编码格式不统一,就会出现问题 数据库读取的时候在mysqli_connect()之后要设置连接字符编码mysq ...

  9. 前端性能优化---减少http请求数量和减少请求资源的大小

    减少http请求数量:就是资源的合并 减少http请求大小:就是资源的压缩   一.资源合并的原理:   资源不合并的缺点: 1.文件和文件之间有插入请求----请求a.js,b.js,c.js(三行 ...

  10. oracle 行转列函数pivot和unpivot

    今天接到业务部门的一个需求,需要对同一公司的不同财务指标进行排序,需要用到oracle的行转列函数unpivot. 财务报表的表结构为: 要实现业务部门的排序筛选功能,需要首先将行数据转为列数据: 使 ...