斑马斑马-23-DjangoRESTFramework(DRF)系列教程
学习和使⽤⼀个技术、官⽅⽂档⾄关重要。
⼀、认证Authentication
Auth needs to be pluggable.— Jacob Kaplan-Moss, ⼀⾔以蔽之:认证需要可插拔
1、(如何确定⾝份验证)
常见的认证⽅式
A:BasicAuthentication
This authentication scheme uses HTTP Basic Authentication, signed against a user's username and password. Basic authentication is generally only appropriate for testing.
Note: If you use BasicAuthentication in production you must ensure that your API is only available over https. You should also ensure that your API clients will always re-request the username and password at login, and will never store those de 使⽤HTTP基本认证,基于⽤于名和密码。多⽤于测试。如果⽤于⽣产环境,确保是https,⽽且要确保进⾏持久化存储
B:SessionAuthentication
This authentication scheme uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website.
If successfully authenticated, SessionAuthentication provides the following credentials.
* request.user will be a Django User instance.
* request.auth will be None.
Warning: Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected.
CSRF validation in REST framework works slightly differently to standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF token 该认证使⽤django默认的后端session验证。
如果成功通过验证,会提供(request.user、request.auth)
为了保证登录受保护,请始终使⽤Django标准视图登录
1:Setting the authentication scheme 设置认证⽅案(setting⽂件进⾏全局)
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
]}
2:Setting the authentication scheme 设置认证⽅案(类视图)
dels import BookInfo, HeroInfo
from APP01.serializer import BookInfoSerializer, HeroInfoSerializer
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from sponse import Response
from rest_framework.views import APIView
from rest_framework import status
# GenericAPIView 进⼀步封装,把调⽤的类封装出来
class BookAPIView(APIView):
'''
查询所有图书,增加图书
'''
authentication_classes = (SessionAuthentication, BasicAuthentication)
permission_classes = (IsAuthenticated,)
def get(self, request, format=None):
"""
查询所有图书
路由:GET /books/info?page=1&page_size=5
"""
book_list = BookInfo.objects.all()
# 2:创建可以序列化列表的序列化器
serializer_list = BookInfoSerializer(instance=book_list, many=True)
# 3:转换数据
# return JsonResponse(serializer_list.data, safe=False)
return Response(serializer_list.data, status=status.HTTP_200_OK)
views中进⾏视图设置
⼆、权限
Authentication or identification by itself is not usually sufficient to gain access to information or code. For that, the entity requesting access must have authorization.
⾝份验证或⾝份识别本⾝通常不⾜以获取信息或代码的访问权限。因此,请求访问的实体必须具有授权。
1、(如何确定权限)
常见的权限类型
AllowAny(所有⽤户)
AllowAny权限类将允许不受限制的访问,⽽不管该请求是否已通过⾝份验证或未经⾝份验证。
IsAuthenticated(注册⽤户)
IsAuthenticated 权限类将拒绝任何未经⾝份验证的⽤户的权限,并允许其他权限。如果你希望你的API仅供注册⽤户访问,则此权限适⽤。
如果你希望你的API允许匿名⽤户读取权限,并且只允许对已通过⾝份验证的⽤户进⾏写⼊权限,则此权限是适合的。
IsAdminUser(管理员⽤户)
除⾮user.is_staff为True,否则IsAdminUser权限类将拒绝任何⽤户的权限,在这种情况下将允许权限。
如果你希望你的API只能被部分受信任的管理员访问,则此权限是适合的。
IsAuthenticatedOrReadOnly
IsAuthenticatedOrReadOnly 将允许经过⾝份验证的⽤户执⾏任何请求。只有当请求⽅法是“安全”⽅法(GET, HEAD 或 OPTIONS)之⼀时,才允许未经授权的⽤户请求。如果你希望你的API允许匿名⽤户读取权限,并且只允许对已通过⾝份验证的⽤户进⾏写⼊权限,则此权限是适合的。
1:Setting the permission policy 设置权限⽅案(setting⽂件进⾏全局)
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
2:Setting the permission policy 设置权限⽅案(局部全局:views.py)
permission_classes = (IsAuthenticated,) #局部权限django admin 自定义页面
3:测试,管理员登录
dels import BookInfo, HeroInfo
from APP01.serializer import BookInfoSerializer, HeroInfoSerializer
from rest_framework.viewsets import ModelViewSet
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated, AllowAny,IsAdminUser
# GenericAPIView 进⼀步封装,把调⽤的类封装出来
class BookAPIView(ModelViewSet):
'''
查询所有图书,增加图书
'''
# 1:局部认证
authentication_classes = [SessionAuthentication]
# 2:局部权限
permission_classes = [IsAdminUser]
queryset = BookInfo.objects.all()
serializer_class = BookInfoSerializer
View15.py
2:创建管理员
python manage.py createsuperuser
⽤户名:admin 密码:1
3:通过django中admin⽤户登录,
4:查看
三、限流
, ⼀⾔以蔽之:限制响应次数
1、(如何确定限流)
As with permissions and authentication, throttling in REST framework is always defined as a list of classes.
Before running the main body of the view each throttle in the list is checked. If any throttle check fails an exceptions.
Throttled exception will be raised, and the main body of the view will not run.
常见的限流类型
AnonRateThrottle
The AnonRateThrottle will only ever throttle unauthenticated users. The IP address of the incoming r
equest is used to generate a unique key to throttle against.
The allowed request rate is determined from one of the following (in order of preference).
The rate property on the class, which may be provided by overriding AnonRateThrottle and setting the property.
The DEFAULT_THROTTLE_RATES['anon'] setting.
AnonRateThrottle is suitable if you want to restrict the rate of requests from unknown sources.
限制匿名⽤户
UserRateThrottle
The UserRateThrottle will throttle users to a given rate of requests across the API. The user id is used to generate a unique key to throttle against. Unauthenticated requests will fall back to using the IP address of the incoming request to generat The allowed request rate is determined from one of the following (in order of preference).
The rate property on the class, which may be provided by overriding UserRateThrottle and setting the property.
The DEFAULT_THROTTLE_RATES['user'] setting.
限流⽅案
1:Setting the throttle policy 设置限流⽅案(setting⽂件进⾏全局)
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle'
],
'DEFAULT_THROTTLE_RATES': {
'anon': '100/day',
'user': '1000/day'
}
2:Setting the throttle policy 设置局部限流⽅案(views⽂件进⾏)
dels import BookInfo, HeroInfo
from APP01.serializer import BookInfoSerializer, HeroInfoSerializer
from rest_framework.viewsets import ModelViewSet
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated, AllowAny, IsAdminUser
from rest_framework.throttling import AnonRateThrottle,UserRateThrottle
# GenericAPIView 进⼀步封装,把调⽤的类封装出来
class BookAPIView(ModelViewSet):
'''
查询所有图书,增加图书
'''
# 1:局部认证
authentication_classes = [SessionAuthentication]
# 2:局部权限
permission_classes = [IsAdminUser]
# 3:局部限流
throttle_classes = [UserRateThrottle]
queryset = BookInfo.objects.all()
serializer_class = BookInfoSerializer
view15.py
3:测试
四、分页
Django provides a few classes that help you manage paginated data – that is, data that’s split across several pages, with “Previous/Next” links. Django提供了上⼀页/下⼀页的⽅式来进⾏分页
1、(如何确定分页)
1:Setting the pagination policy 设置分页⽅案(setting⽂件进⾏全局)
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'PAGE_SIZE': 100
}
2:Setting the pagination policy 设置局部限流⽅案(views⽂件进⾏)
dels import BookInfo, HeroInfo
from APP01.serializer import BookInfoSerializer, HeroInfoSerializer
from rest_framework.viewsets import ModelViewSet
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated, AllowAny, IsAdminUser
from rest_framework.throttling import AnonRateThrottle, UserRateThrottle
from rest_framework.pagination import LimitOffsetPagination,PageNumberPagination
# GenericAPIView 进⼀步封装,把调⽤的类封装出来
class BookAPIView(ModelViewSet):
'''
查询所有图书,增加图书
'''
queryset = BookInfo.objects.all()
serializer_class = BookInfoSerializer
# 1:局部分页
pagination_class = PageNumberPagination
views.py
2、⾃定义分页
PageNumberPagination中存在⼀个问题,即:page_size ⽆法修改,我们可以通过⾃定义类来实现
dels import BookInfo, HeroInfo
from APP01.serializer import BookInfoSerializer, HeroInfoSerializer
from rest_framework.viewsets import ModelViewSet
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated, AllowAny, IsAdminUser
from rest_framework.throttling import AnonRateThrottle, UserRateThrottle
from rest_framework.pagination import LimitOffsetPagination,PageNumberPagination
# GenericAPIView 进⼀步封装,把调⽤的类封装出来
# ⾃定义分页对象
class MyPageNumberPagination(PageNumberPagination):
page_size_query_param = "page_size"
max_page_size = 5 #最⼤不能超过5
class BookAPIView(ModelViewSet):
'''
查询所有图书,增加图书
'''
queryset = BookInfo.objects.all()
serializer_class = BookInfoSerializer
# 1:⾃定义分页
pagination_class = MyPageNumberPagination
view16.py
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论