DRF快速开发

接口文档

https://open.weibo.com/wiki/2/comments/show

自测环境

# 配置环境
import os

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "day06.settings")
    import django
    django.setup()
    # 代码都要写在这个下面
    from app01 import models

国际化

LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = False

视图类

# GenericAPIView  继承了APIView  ,多了属性和方法
    from rest_framework.generics import GenericAPIView
  -属性(先记两个)
      -queryset = None
      -serializer_class = None
  -方法
      -get_queryset
      -get_object
      -get_serializer
    
# 5个视图扩展类(不是视图类,没有集成APIView,需要配合GenericAPIView)
  from rest_framework.mixins import
  CreateModelMixin,
  ListModelMixin,
  DestroyModelMixin,
  RetrieveModelMixin,
  UpdateModelMixin
  
# 9个视图子类 
  from rest_framework.generics import
  CreateAPIView,
  ListAPIView,
  DestroyAPIView,
  RetrieveAPIView,
  UpdateAPIView
  ListCreateAPIView,
  RetrieveUpdateAPIView,
  RetrieveUpdateDestroyAPIView,
  RetrieveDestroyAPIView

# 视图集
  from rest_framework.viewsets import
  # 两个视图类
  ModelViewSet,ReadOnlyModelViewSet
  # 视图类
  ViewSet,GenericViewSet  # 自动生成路由
  # 魔法类
  ViewSetMixin  # 自动生成路由

认证,权限,频率

auth.py

from rest_framework.authentication import BaseAuthentication
from .models import User, UserToken
from rest_framework.exceptions import AuthenticationFailed


class LoginAuth(BaseAuthentication):             # 认证类
    def authenticate(self, request):
        token = request.query_params.get('token')  # 带在地址里
        user_token = UserToken.objects.filter(token=token).first()
        if user_token:  # 登入了
            return user_token.user, token  # 第一个:request.user, 第二个:request.auth
        else:
            raise AuthenticationFailed('您没有登入!')  # 如果没有登入抛异常

from rest_framework.permissions import DjangoObjectPermissions class UserPermission(DjangoObjectPermissions): # 权限类 def has_permission(self, request, view): self.message = '您是:%s, 没有权限' % request.user.get_user_type_display() # 没有权限提示 user_type = request.user.user_type if user_type < 3: return True else: return False

from rest_framework.throttling import BaseThrottle, ScopedRateThrottle class IPThrottle(ScopedRateThrottle): # 频率类 scope = 'minute_3' # 随便写 def get_cache_key(self, request, view): return request.META.get('REMOTE_ADDR') # 客户端ip # return request.user.id # 用户id

views.py

from .serializer import *
from rest_framework.viewsets import GenericViewSet
from rest_framework.response import Response
from rest_framework.decorators import action
from .auth import LoginAuth


class TestView(GenericViewSet):
    authentication_classes = [LoginAuth, ]   # 局部认证
    # authentication_classes = []  # 局部禁用 
    permission_classes = [UserPermission, ]  # 局部权限
    # permission_classes = []  # 局部禁用 
    throttle_classes = [IPThrottle]          # 局部频率
    # throttle_classes = []  # 局部禁用
    queryset = Publish.objects.all()
    serializer_class = PublishSerialzier

    def get_queryset(self):
        # 根据请求地址,返回get_queryset不一样
        if self.action == 'login':
            return Author.objects.all()
        else:
            return self.queryset

settings.py

# 全局配置:配置文件中
REST_FRAMEWORK={
  "DEFAULT_AUTHENTICATION_CLASSES":["app01.auth.LoginAuth",], # 认证
  "DEFAULT_PERMISSION_CLASSES":["app01.auth.UserPermission",],# 权限
  "DEFAULT_THROTTLE_CLASSES":('app01.auth.IPThrottle'),        # 频率
  "DEFAULT_THROTTLE_RATES": {
     'minute_3': '3/m' # minute_3是scope的字符串,一分钟访问3次
     'minute_5''5/m'
     },
}     

ViewSet

models.py

class User(models.Model):
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=32)
    user_type = models.IntegerField(choices=((1, '超级管理员'), (2, '普通管理员'), (3, '普通用户')))
    # gender=models.IntegerField(choices=((1,"男"),(2,"女"),(0,"未知"))) # 1:男  2:女 0:未知
    # user对象.get_字段名_display()  快速取出gender数字对应的中文


class UserToken(models.Model):
    user = models.OneToOneField(to=User,on_delete=models.CASCADE)
    token = models.CharField(max_length=32)

views.py

class UserView(ViewSet):
    @action(methods=['POST'], detail=False)
    def login(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生成不重复的串---》理论上不重复
            token = str(uuid.uuid4())  # 伪随机数生成,没有参数,重复概率,比其他的高一些
            UserToken.objects.update_or_create(user=user, defaults={'token': token})  # 如果存在就更新,如果不存在就新增
            return Response({'code': 100, 'msg': '登陆成功', 'token': token})
        else:
            return Response({'code': 101, 'msg': '用户名或密码错误'})

urls.py

from app01 import views
from rest_framework.routers import SimpleRouter
router=SimpleRouter()
router.register('user',views.UserView,'user')

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include(router.urls)),
]

GenericViewSet

views.py

from .serializer import *
from rest_framework.viewsets import GenericViewSet
from rest_framework.response import Response
from rest_framework.decorators import action


class TestView(GenericViewSet):
    queryset = Publish.objects.all()
    serializer_class = PublishSerialzier

    def get_queryset(self):
        # 根据请求地址,返回get_queryset不一样
        if self.action == 'login':
            return Author.objects.all()
        else:
            return self.queryset

    def get_serializer_class(self):
        if self.action == 'login':
            return AuthorSerialzier
        else:
            return self.serializer_class

    # 只要是继承ViewSetMixin视图类中方法,都可以加action装饰器,只要加了,自动生成路由会多生成 - -》127.0.0.1: 8080 / test / login:get或post都能触发
    @action(methods=['GET', 'POST'], detail=False)
    def login(self, request):
        obj = self.get_queryset()
        return Response('get_login')

    # 如果写法如下,生成的路径是127.0.0.1:8080/test/数字/login
    @action(methods=['GET', 'POST'], detail=True)
    def logout(self, request):
        return Response('get_logout')

urls.py

from django.contrib import admin
from django.urls import path, include
from app01 import views
from rest_framework.routers import SimpleRouter

router = SimpleRouter()
router.register('test', views.TestView, 'test')
urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/v1/', include(router.urls)),
]

ModelViewSet

views.py

from .serializer import *
from rest_framework.viewsets import ModelViewSet, ReadOnlyModelViewSet


class PublishView(ModelViewSet):
    queryset = Publish.objects.all()
    serializer_class = PublishSerialzier

urls.py

from django.contrib import admin
from django.urls import path, include
from app01 import views
from rest_framework.routers import SimpleRouter

router = SimpleRouter()
router.register('publish', views.PublishView, 'publish')  # 注册路由
urlpatterns = [
    path('admin/', admin.site.urls),
    # path('publishs/', views.PublishView.as_view()),
    # path('publishss/<int:pk>', views.PublishDetalView.as_view()),
    path('/api/v1', include(router.urls)),  # 方式二
]
# 把路由加入到url列表中
urlpatterns += router.urls  # 方式一

9个视图子类

views.py

from .serializer import *
from rest_framework.generics import CreateAPIView, ListAPIView, DestroyAPIView, RetrieveAPIView, UpdateAPIView,ListCreateAPIView, RetrieveUpdateAPIView, RetrieveUpdateDestroyAPIView, RetrieveDestroyAPIView


# class PublishView(CreateAPIView):  新增一个
# class PublishView(ListAPIView):  查所有
class PublishView(ListCreateAPIView):  # 新增一个+查所有
    queryset = Publish.objects.all()
    serializer_class = PublishSerialzier


# class PublishDetalView(RetrieveAPIView):  # 查一条
# class PublishDetalView(DestroyAPIView):  # 删除
# class PublishDetalView(UpdateAPIView):  # 改
# class PublishDetalView(RetrieveDestroyAPIView):  # 查一条+删除
# class PublishDetalView(RetrieveUpdateAPIView):  # 查一条+改
class PublishDetalView(RetrieveUpdateDestroyAPIView):  # 查一条+改+删除
    queryset = Publish.objects.all()
    serializer_class = PublishSerialzier

GenericAPIView+5个视图扩展类

from rest_framework.generics import GenericAPIView
from .serializer import *
from rest_framework.mixins import CreateModelMixin, ListModelMixin, DestroyModelMixin, RetrieveModelMixin, UpdateModelMixin


class PublishView(GenericAPIView, ListModelMixin, CreateModelMixin):
    queryset = Publish.objects.all()
    serializer_class = PublishSerialzier

    def get(self, request):
        return super().list(request)

    def post(self, request):
        return super().create(request)


class PublishDetalView(GenericAPIView, UpdateModelMixin, RetrieveModelMixin, DestroyModelMixin):
    queryset = Publish.objects.all()
    serializer_class = PublishSerialzier

    def get(self, request, *args, **kwargs):
        return super().retrieve(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        return super().update(request, *args, **kwargs)

    def delete(self, request, *args, **kwargs):
        return super().destroy(request, *args, **kwargs)

GenericAPIView

views.py

from rest_framework.response import Response
from rest_framework.generics import GenericAPIView
from .serializer import *


class PublishView(GenericAPIView):
    queryset = Publish.objects.all()
    serializer_class = PublishSerialzier

    def get(self, request):
        obj = self.get_queryset()
        ser = self.get_serializer(instance=obj, many=True)
        return Response(ser.data)

    def post(self, request):
        ser = self.get_serializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '新增失败', 'data': ser.data})
        return Response({'code': 101, 'msg': '新增成功', 'err': ser.errors})


class PublishDetalView(GenericAPIView):
    queryset = Publish.objects.all()
    serializer_class = PublishSerialzier

    def get(self, request, *args, **kwargs):
        obj = self.get_object()
        ser = self.get_serializer(instance=obj)
        return Response(ser.data)

    def put(self, request, *args, **kwargs):
        obj = self.get_object()
        ser = self.get_serializer(instance=obj, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '修改成功', 'data': ser.data})
        return Response({'code': 101, 'msg': '修改出错', 'err': ser.errors})

    def delete(self, request, *args, **kwargs):
        self.get_object().delete()
        return Response({'code': 100, 'msg': '删除成功'})

APIView

models.py

from django.db import models


class Book(models.Model):
    name = models.CharField(max_length=32)
    price = models.DecimalField(decimal_places=2, max_digits=5)
    publish = models.ForeignKey(to='Publish', on_delete=models.CASCADE)
    authors = models.ManyToManyField(to='Author')

    # 定制序列化字段  第二种:表模型中写方法
    @property  # 把方法包装成数据属性
    def price_info(self):
        return "价格是:" + str(self.price)

    def authors(self):
        # 如果有外键关联, 假设作者好几个
        ser = self.author.all()
        for obj in ser:
            dict['name'] = obj.name
        return dict  # [{}, {}]

serializer.py

from rest_framework import serializers
from .models import Book
from rest_framework.exceptions import ValidationError


class BookSerializer(serializers.Serializer):
    id = serializers.CharField(read_only=True)
    name = serializers.CharField(max_length=8, min_length=3)  # max_length=32,min_length=3  反序列化保存校验数据的时候用
    price = serializers.CharField(required=False)  # models中使用了DecimalField,这个位置使用了CharField会把小数类型转成字符串
    author = serializers.CharField(required=False)

    # 定制序列化字段  第一种:在序列化类中写
    price_info = serializers.SerializerMethodField()  # 必须配合一个方法,方法名get_字段名

    def get_price_info(self, obj):  # 方法返回什么,字段就是什么,obj是当前序列化到的单个对象
        return "价格是:" + str(obj.price)  # python是动态强类型语言--》强类型是:不同类型之间不允许直接运算

    def get_author_info(self, obj):
        return {'name': obj.author.name, 'age': obj.author.age}  # 如果author是外键字段可以连表查询作者信息表

    # 定制序列化字段  第二种  第二步在models中写方法,这里字段名就是models的方法名,price_info方法返回什么,这个字段就是什么
    price_info = serializers.CharField(read_only=True)  # 只用来做序列化

    # 新增
    def create(self, validated_data):
        # validated_data校验过后的数据
        # 手动存到book表中
        book = Book.objects.create(**validated_data)
        # book=Book.objects.create(name=validated_data.get('name'))
        return book  # 不要忘记返回book对象

    # 修改
    def update(self, instance, validated_data):
        # validated_data校验过后的数据,instance 是要修改的对象
        instance.name = validated_data.get('name')
        instance.price = validated_data.get('price')
        instance.author = validated_data.get('author')
        instance.save()  # 模型对象自带的save,保存到数据库中
        return instance  # 要忘记返回instance对象

    # 局部钩子
    # 字段有自己的校验:max_length .... ,再校验,就可以写局部钩子
    def validate_name(self, attr):
        # attr就是前端传入的数据
        # 名字不能以sb开头
        if attr.startswith('sb'):
            raise ValidationError("名字不能以sb开头")
        else:
            return attr  # 没有问题,正常返回

    # 先走字段自己规则,再走局部钩子,再走全局钩子
    # 全局钩子
    def validate(self, attrs):
        # attrs校验过后的数据
        if attrs.get('name') == attrs.get('author'):
            raise ValidationError('作者名不能等于书名')
        else:
            return attrs


# 以后使用ModelSerializer跟表模型做绑定,以后这个用的多,不需要重写update和create方法了
class BookSerializer2(serializers.ModelSerializer):
    class Meta:
        model = Book  # 跟那个表有关系
        # fields='__all__' # 所有字段
        # id是从表模型中映射过来的,auto,它会不要求你传
        # price_info:它不是数据库中字段
        # 即便定制了字段,也要在fields中注册
        fields = ['id', 'name', 'price', 'author', 'price_info']
        # 原来的字段参数,通过extra_kwargs传进去
        extra_kwargs = {
            'name': {'write_only': True, 'max_length': 8, 'min_length': 3}
        }

    # 重写字段
    # 局部和全局钩子跟之前一样

views.py

from rest_framework.response import Response
from rest_framework.views import APIView
from .models import Book
from .serializer import BookSerializer


class BookView(APIView):
    def get(self, request):
        book_list = Book.objects.all()
        ser = BookSerializer(instance=book_list, many=True)
        return Response(ser.data)

    def post(self, request):
        ser = BookSerializer(data=request.data)  # 反序列化,保存   data参数
        # 效验数据
        if ser.is_valid():  # 如果True 表示通过
            # 如果instance为None,调用save本质会调用create--》父类create直接抛异常,所以我们要重写
            ser.save()  # 就会保存,重写create方法,如果不重写,我们不知道存到哪个表中
            return Response(ser.data)
        return Response({'code': 101, 'msg': '数据校验失败', 'err': ser.errors})


class BookDetalView(APIView):
    def get(self, request, pk):
        book = Book.objects.filter(pk=pk).first()
        ser = BookSerializer(instance=book)  # 如果是单条记录,many不传,就是false
        return Response(ser.data)

    def delete(self, request, pk):
        res = Book.objects.filter(pk=pk).delete()
        if res[0] > 0:
            return Response({'code': 100, 'msg': '删除成功'})
        else:
            return Response({'code': 103, 'msg': '数据不存在'})

    def put(self, request, pk):
        # 修改:用什么数据,修改哪个对象?
        book = Book.objects.filter(pk=pk).first()
        # 既有instance,又有data,表示修改
        ser = BookSerializer(instance=book, data=request.data)
        if ser.is_valid():
            # 重写update方法
            ser.save()  # 调用save---》内部根据instance判断是触发create还是update
            return Response(ser.data)
        return Response({'code': 102, 'msg': '修改出错', 'err': ser.errors})

urls.py

from app01 import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('books/', views.BookView.as_view()),
    path('books/<int:pk>', views.BookDetalView.as_view()),
]

字段类型

字段字段构造方式
BooleanField BooleanField()
NullBooleanField NullBooleanField()
CharField CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)
EmailField EmailField(max_length=None, min_length=None, allow_blank=False)
RegexField RegexField(regex, max_length=None, min_length=None, allow_blank=False)
SlugField SlugField(maxlength=50, min_length=None, allow_blank=False) 正则字段,验证正则模式 [a-zA-Z0-9-]+
URLField URLField(max_length=200, min_length=None, allow_blank=False)
UUIDField UUIDField(format=’hex_verbose’) format: 1) 'hex_verbose'"5ce0e9a5-5ffa-654b-cee0-1238041fb31a" 2) 'hex'"5ce0e9a55ffa654bcee01238041fb31a" 3)'int' - 如: "123456789012312313134124512351145145114" 4)'urn' 如: "urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a"
IPAddressField IPAddressField(protocol=’both’, unpack_ipv4=False, **options)
IntegerField IntegerField(max_value=None, min_value=None)
FloatField FloatField(max_value=None, min_value=None)
DecimalField DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None) max_digits: 最多位数 decimal_palces: 小数点位置
DateTimeField DateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None)
DateField DateField(format=api_settings.DATE_FORMAT, input_formats=None)
TimeField TimeField(format=api_settings.TIME_FORMAT, input_formats=None)
DurationField DurationField()
ChoiceField ChoiceField(choices) choices与Django的用法相同
MultipleChoiceField MultipleChoiceField(choices)
FileField FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)
ImageField ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)
ListField ListField(child=, min_length=None, max_length=None)
DictField DictField(child=)

选项参数

参数名称作用
max_length 最大长度(CharField)
min_lenght 最小长度(CharField)
allow_blank 是否允许为空(CharField)
trim_whitespace 是否截断空白字符(CharField)
max_value 最小值 (IntegerField)
min_value 最大值(IntegerField)

通用参数

参数名称说明
read_only 表明该字段仅用于序列化输出,默认False
write_only 表明该字段仅用于反序列化输入,默认False
required 表明该字段在反序列化时必须输入,默认True
default 反序列化时使用的默认值
allow_null 表明该字段是否允许传入None,默认False
validators 该字段使用的验证器(不太用)
error_messages 包含错误编号与错误信息的字典
label 用于HTML展示API页面时,显示的字段名称
help_text 用于HTML展示API页面时,显示的字段帮助提示信息
posted @ 2022-06-20 11:38  Snails蜗牛  阅读(77)  评论(0编辑  收藏  举报