1 认证
1.1 认证的写法
1 写一个类,继承BaseAuthentication,重写authenticate,认证的逻辑写在里面,认证通过,返回两个值(user,auth),一个值最终给了Requet对象的user,认证失败,抛异常:APIException或者AuthenticationFailed
2 全局使用,局部使用
1.2 认证的源码分析
def _authenticate(self):
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()
1.3 认证组件的使用
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from app01.models import UserToken
class MyAuthentication(BaseAuthentication):
def authenticate(self, request):
token=request.GET.get('token')
if token:
user_token=UserToken.objects.filter(token=token).first()
if user_token:
return user_token.user,token
else:
raise AuthenticationFailed('认证失败')
else:
raise AuthenticationFailed('请求地址中需要携带token')
REST_FRAMEWORK={
"DEFAULT_AUTHENTICATION_CLASSES":["app01.app_auth.MyAuthentication",]
}
authentication_classes=[MyAuthentication]
authentication_classes=[]
2 权限
2.1 权限源码分析
def check_permissions(self, request):
for permission in self.get_permissions():
if not permission.has_permission(request, self):
self.permission_denied(
request, message=getattr(permission, 'message', None)
)
2.2 权限的使用
from rest_framework.permissions import BasePermission
class UserPermission(BasePermission):
def has_permission(self, request, view):
user=request.user
print(user.get_user_type_display())
if user.user_type==1:
return True
else:
return False
class TestView(APIView):
permission_classes = [app_auth.UserPermission]
REST_FRAMEWORK={
"DEFAULT_AUTHENTICATION_CLASSES":["app01.app_auth.MyAuthentication",],
'DEFAULT_PERMISSION_CLASSES': [
'app01.app_auth.UserPermission',
],
}
class TestView(APIView):
permission_classes = []
2.3 内置权限(了解)
from rest_framework.permissions import IsAdminUser
from rest_framework.authentication import SessionAuthentication
class Test3View(APIView):
authentication_classes = [SessionAuthentication, ]
permission_classes = [IsAdminUser, ]
def get(self, request, *args, **kwargs):
return APIResponse(msg='这是Test3View测试数据,超级管理员可以看')
2.4 自定义认证、权限
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.permissions import BasePermission
from app01.models import UserToken
class MyAuthentication(BaseAuthentication):
def authenticate(self, request):
token = request.GET.get('token')
if token:
user_token = UserToken.objects.filter(token=token).first()
if user_token:
return user_token.user, token
else:
raise AuthenticationFailed('认证失败')
else:
raise AuthenticationFailed('请求地址中未携带token')
class UserPermission(BasePermission):
def has_permission(self, request, view):
user = request.user
print(user.get_user_type_display())
if user.user_type == 1:
return True
else:
return False
class User(models.Model):
username = models.CharField(max_length=32)
password = models.CharField(max_length=32)
user_type = models.IntegerField(choices=((1, '超级用户'), (2, '普通用户'), (3, '二笔用户')))
class Meta:
verbose_name_plural = '用户表'
class UserToken(models.Model):
token = models.CharField(max_length=64)
user = models.OneToOneField(to='User', on_delete=models.CASCADE)
class Meta:
verbose_name_plural = '用户token表'
class LoginView(APIView):
authentication_classes = []
def post(self, request):
username = request.data.get('username')
password = request.data.get('password')
user = User.objects.filter(username=username, password=password).first()
if user:
token = uuid.uuid4()
UserToken.objects.update_or_create(defaults={'token': token}, user=user)
return APIResponse(token=token)
else:
return APIResponse(code=101, msg='用户名或密码错误')
class TestView(APIView):
authentication_classes = [MyAuthentication, ]
permission_classes = [UserPermission, ]
def get(self, request, *args, **kwargs):
return APIResponse(msg='这是TestView测试数据')
class Test2View(APIView):
authentication_classes = [MyAuthentication, ]
def get(self, request, *args, **kwargs):
return APIResponse(msg='这是Test2View测试数据')
3 频率
3.1 内置的频率限制(限制未登录用户)
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttling.AnonRateThrottle',
),
'DEFAULT_THROTTLE_RATES': {
'anon': '3/m',
}
}
from rest_framework.permissions import IsAdminUser
from rest_framework.authentication import SessionAuthentication,BasicAuthentication
class Test4View(APIView):
authentication_classes = []
permission_classes = []
def get(self, request, *args, **kwargs):
return APIResponse(msg='这是Test4View测试数据,登录用户访问频次,全局')
-------------------------------------------------------------------------------------
from rest_framework.permissions import IsAdminUser
from rest_framework.authentication import SessionAuthentication,BasicAuthentication
from rest_framework.throttling import AnonRateThrottle
class Test5View(APIView):
authentication_classes = []
permission_classes = []
throttle_classes = [AnonRateThrottle, ]
def get(self, request, *args, **kwargs):
return APIResponse(msg='这是Test5View测试数据,登录用户访问频次,局部')
3.2 内置频率限制之限制登录用户的访问频次
全局:在setting中
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle'
),
'DEFAULT_THROTTLE_RATES': {
'user': '10/m',
'anon': '5/m',
}
局部配置:
在视图类中配一个就行
class Test6View(APIView):
authentication_classes = [SessionAuthentication]
permission_classes = []
throttle_classes = [AnonRateThrottle, UserRateThrottle]
def get(self, request, *args, **kwargs):
return APIResponse(msg='这是Test6View测试数据,录用户每分钟访问10次,未登录用户访问5次')
3.3 根据ip进行频率限制
from rest_framework.throttling import ScopedRateThrottle,SimpleRateThrottle
class MyThrottle(SimpleRateThrottle):
scope='luffy'
def get_cache_key(self, request, view):
print(request.META.get('REMOTE_ADDR'))
return request.META.get('REMOTE_ADDR')
throttle_classes = [MyThrottle,]
REST_FRAMEWORK={
'DEFAULT_THROTTLE_CLASSES': (
'utils.throttling.MyThrottle',
),
'DEFAULT_THROTTLE_RATES': {
'luffy': '3/m'
},
}
3.4 自定义频率
-
def allow_request(self, request, view):
-
def wait(self):
import time
class IPThrottle():
VISIT_DIC = {}
def __init__(self):
self.history_list=[]
def allow_request(self, request, view):
'''
#(1)取出访问者ip
#(2)判断当前ip不在访问字典里,添加进去,并且直接返回True,表示第一次访问,在字典里,继续往下走
#(3)循环判断当前ip的列表,有值,并且当前时间减去列表的最后一个时间大于60s,把这种数据pop掉,这样列表中只有60s以内的访问时间,
#(4)判断,当列表小于3,说明一分钟以内访问不足三次,把当前时间插入到列表第一个位置,返回True,顺利通过
#(5)当大于等于3,说明一分钟内访问超过三次,返回False验证失败
'''
ip=request.META.get('REMOTE_ADDR')
ctime=time.time()
if ip not in self.VISIT_DIC:
self.VISIT_DIC[ip]=[ctime,]
return True
self.history_list=self.VISIT_DIC[ip]
while True:
if ctime-self.history_list[-1]>60:
self.history_list.pop()
else:
break
if len(self.history_list)<3:
self.history_list.insert(0,ctime)
return True
else:
return False
def wait(self):
ctime=time.time()
return 60-(ctime-self.history_list[-1])
SimpleRateThrottle源码分析
def get_rate(self):
"""
Determine the string representation of the allowed request rate.
"""
if not getattr(self, 'scope', None):
msg = ("You must set either `.scope` or `.rate` for '%s' throttle" %
self.__class__.__name__)
raise ImproperlyConfigured(msg)
try:
return self.THROTTLE_RATES[self.scope]
except KeyError:
msg = "No default throttle rate set for '%s' scope" % self.scope
raise ImproperlyConfigured(msg)
def parse_rate(self, rate):
"""
Given the request rate string, return a two tuple of:
<allowed number of requests>, <period of time in seconds>
"""
if rate is None:
return (None, None)
num, period = rate.split('/')
num_requests = int(num)
duration = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}[period[0]]
return (num_requests, duration)
def allow_request(self, request, view):
if self.rate is None:
return True
self.key = self.get_cache_key(request, view)
if self.key is None:
return True
self.history = self.cache.get(self.key, [])
self.now = self.timer()
while self.history and self.now - self.history[-1] >= self.duration:
self.history.pop()
if len(self.history) >= self.num_requests:
return self.throttle_failure()
return self.throttle_success()
4 过滤组件使用
INSTALLED_APPS = [
'django_filters',
]
'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
class BookView(ListAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
filter_fields = ('name',)
5 排序
from rest_framework.generics import ListAPIView
from rest_framework.filters import OrderingFilter
from app01.models import Book
from app01.ser import BookSerializer
class Book2View(ListAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
filter_backends = [OrderingFilter]
ordering_fields = ('id', 'price')
path('books2/', views.Book2View.as_view()),
]
http://127.0.0.1:8000/books2/?ordering=-price
http://127.0.0.1:8000/books2/?ordering=price
http://127.0.0.1:8000/books2/?ordering=-id
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 现代计算机视觉入门之:什么是图片特征编码
· .NET 9 new features-C#13新的锁类型和语义
· Spring AI + Ollama 实现 deepseek-r1 的API服务和调用
· 《HelloGitHub》第 106 期
· 数据库服务器 SQL Server 版本升级公告
· 深入理解Mybatis分库分表执行原理
· 使用 Dify + LLM 构建精确任务处理应用