首先我们为了方便下面的练习,先创建一个新的子应用api
python manage.py startapp api
注册创建的子应用:
INSTALLED_APPS = [
...
'api', # drf的组件使用
]
python manage.py createsuperuser
python manage.py changepassword 用户名
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
可以在配置文件中配置全局默认的认证方法,查看全局的默认配置:
DEFAULTS = {
...
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication', # session认证
'rest_framework.authentication.BasicAuthentication' # 基本认证
],
...
}
常见的认证方式:cookie、session、token
from rest_framework import status
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.response import Response
from rest_framework.views import APIView
class StudentsView(APIView):
authentication_classes = [SessionAuthentication, BasicAuthentication]
def get(self, request):
if not request.user.id:
return Response({'msg': '未验证通过!!'}, status=status.HTTP_401_UNAUTHORIZED)
return Response({'msg': '验证成功!!'}, status=status.HTTP_200_OK)
from django.contrib.auth import get_user_model
from rest_framework.authentication import BaseAuthentication
class UserAuthentication(BaseAuthentication):
"""
自定义认证方法
"""
def authenticate(self, request):
"""
认证方法
:param request: 客户端发送的http请求对象
:return: True: (user,None) False: (None)
"""
user = request.query_params.get('user')
pwd = request.query_params.get('pwd')
if user != 'ycx' and pwd != '........':
return None
user = get_user_model().objects.first()
return (user, None)
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from .authentication import UserAuthentication
class StudentsView(APIView):
authentication_classes = [UserAuthentication]
def get(self, request):
if not request.user.id:
return Response({'msg': '未验证通过!!'}, status=status.HTTP_401_UNAUTHORIZED)
return Response({'msg': '验证成功!!'}, status=status.HTTP_200_OK)
"""drf配置信息必须全部写在REST_FRAMEWORK配置项中"""
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'api.authentication.UserAuthentication', # 自定义认证
'rest_framework.authentication.SessionAuthentication', # session认证
'rest_framework.authentication.BasicAuthentication', # 基本认证
)
}
权限控制可以限制用户对于视图的访问和对于具有模型对象的访问
对于用户的权限限制,共有两个方面:
class StudentsPreView(GenericAPIView):
"""通用视图类:多个数据操作"""
# 独特操作
queryset = Students.objects.all()
serializer_class = StudentModelSerializers
authentication_classes = [SessionAuthentication]
permission_classes = [IsAuthenticatedOrReadOnly]
def get(self, request):
# 获取查询到的模型数据集
ser = StudentModelSerializers(instance=self.get_queryset(), many=True)
return Response(ser.data, status=status.HTTP_200_OK)
def post(self, request):
ser = self.get_serializer(data=request.data)
# raise_exception:自动将报错信息返回给页面
ser.is_valid(raise_exception=True)
ser.save()
return Response(ser.data, status=status.HTTP_201_CREATED)
如需自定义权限,需继承rest_framework.permissions.BasePermission父类,并实现以下两个任何一个方法或全部
.has_permission(self, request, view):是否可以访问视图, view表示当前视图对象,返回值:True或False,允许访问视图或不允许
.has_object_permission(self, request, view, obj):是否可以访问模型对象, view表示当前视图对象, obj为模型数据对象,返回值:True或False,允许访问模型对象或不允许
定义:自定义permissions.py文件:
from rest_framework.permissions import BasePermission
class StudentsPermission(BasePermission):
"""
自定义权限组件:全局配置或局部配置
"""
def has_permission(self, request, view):
"""
视图权限
:param request:请求对象
:param view:要访问的视图类
:return:True或False
"""
# 获取
name = request.query_params.get('name')
return name == 'ycx'
def has_object_permission(self, request, view, obj):
"""
模型权限
:param request:请求对象
:param view:访问视图对象
:param obj:模型数据对象
:return:True或False
"""
return True
REST_FRAMEWORK = {
# 认证全局配置
'DEFAULT_AUTHENTICATION_CLASSES': (
'api.authentication.UserAuthentication', # 自定义认证
'rest_framework.authentication.SessionAuthentication', # session认证
'rest_framework.authentication.BasicAuthentication', # 基本认证
),
# 权限全局配置
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
'api.permissions.StudentsPermission' # 自定义权限
]
}
使用DEFAULT_THROTTLE_RATES[‘anon’] 来设置频次
使用DEFAULT_THROTTLE_RATES[‘user’] 来设置频次
class StudentsPreView(GenericAPIView):
"""通用视图类:多个数据操作"""
# 独特操作
queryset = Students.objects.all()
serializer_class = StudentModelSerializers
# 限流
throttle_classes = [UserRateThrottle]
def get(self, request):
# 获取查询到的模型数据集
ser = StudentModelSerializers(instance=self.get_queryset(), many=True)
return Response(ser.data, status=status.HTTP_200_OK)
def post(self, request):
ser = self.get_serializer(data=request.data)
# raise_exception:自动将报错信息返回给页面
ser.is_valid(raise_exception=True)
ser.save()
return Response(ser.data, status=status.HTTP_201_CREATED)
在settings.py文件中配置访问频次:
# 限流频率配置
'DEFAULT_THROTTLE_RATES': { # 频率配置
'anon': '2/day', # 针对游客的访问频率进行限制
'user': '5/day', # 针对登录用户的访问频率进行限制
}