一篇文章极速复习drf知识点

serializers.py 文件

对象 -> json 序列化
json -> 对象 反序列化

write_only实例:

from rest_framework.serializers import ModelSerializer
from rest_framework import serializers
from myapi.models import User

class UserModelSerialzier(ModelSerializer):
    password_again = serializers.CharField(max_length=255, write_only=True)

    def validate(self, attrs):
        if attrs.get('password') != attrs.pop('password_again'):
            raise serializers.ValidationError("hello world")
        return super().validate(attrs)

    class Meta:
        model = User
        fields = '__all__'

如果添加模型中不存在的字段且不需要传入就用read_only。

视图(认证、权限、分页)

settings.py文件:

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

views.py文件:

from rest_framework.viewsets import ModelViewSet
from myapi.serializers import UserModelSerialzier
from myapi.models import User
from rest_framework import permissions
from rest_framework import pagination

class MyPermission(permissions.BasePermission):
    def has_permission(self, request, view):
        return True

class LargeResultSetPagination(pagination.PageNumberPagination):
    page_size = 1000                    # 后端显示默认每页显示几条
    page_size_query_param = 'page_size' # 表示每页多少条
    page_query_param = "page"           # 告诉前端发送页数的关键字名,默认为"page",所以可以不写
    max_page_size = 10000               # 限制前端每页最多显示多少条,如果超过了会显示最大条数
# 这样只用访问127.0.0.1/users/?page=1&page_size=2访问时后,会显示每页两条,第一页的数据

class UserModelViewSet(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserModelSerialzier
    permission_classes:permissions.BasePermission = (MyPermission,)
    pagination_class = LargeResultSetPagination

限流

settings.py

REST_FRAMWORK = {
    'DEFAULT_THROTTLE_CLASS':(
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle'
    ),
    'DEFAULT_THROTTLE_RATES': {
        'anon': '100/day',
        'user': '1000/day'
    }
}
posted @ 2023-02-02 04:34  小默同学  阅读(14)  评论(0编辑  收藏  举报