2. DRF入门

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2. DRF入门相关的知识,希望对你有一定的参考价值。

drf介绍

  • Django REST framework (简称:DRF)是一个强大而灵活的 Web API 工具。 遵循RESTFullAPI风格,功能完善,可快速开发API平台。

  • 官网文档:https://www.django-rest-framework.org

  • Django REST framework 最新版使用要求:

    • Python(3.6、3.7、3.8、3.9、3.10)
    • Django(2.2、3.0、3.1、3.2、4.0)

DRF安装与项目配置

DRF安装

pip install djangorestframework
pip install markdown
pip install django-filter

DRF项目配置与初探

  1. 创建django_drf项目

  1. 创建app
E:\\workspace\\django-project\\day1\\django_drf>python manage.py startapp myapp
  1. Settings.py添加项目配置

  1. 项目结构
django_drf
    │  manage.py
    │
    ├─django_drf
    │  │  asgi.py
    │  │  settings.py
    │  │  urls.py
    │  │  wsgi.py
    │  │  __init__.py
    │
    ├─myapp
    │  │  admin.py
    │  │  apps.py
    │  │  models.py
    │  │  tests.py
    │  │  views.py
    │
    └─templates
  1. 主路由配置: django_drf/urls.py
from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path(admin/, admin.site.urls),
    path(myapp/, include(myapp/urls.py))
]
  1. app路由: django_drf/myapp/urls.py
from django.urls import path,re_path
from myapp import views

urlpatterns = [

]

DRF初探之实现用户增删改查API

  1. 定义app数据模型: myapp/models.py
from django.db import models

class User(models.Model):
    name = models.CharField(max_length=32)
    city = models.CharField(max_length=32)
    sex = models.CharField(max_length=16)
    age = models.IntegerField()
  1. 数据同步和迁移
E:\\workspace\\django-project\\day1\\django_drf>python manage.py makemigrations
E:\\workspace\\django-project\\day1\\django_drf>python manage.py migrate
  1. 编写app序列化器文件: myapp/serializers.py
from myapp.models import User
from rest_framework import serializers

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = __all__
  1. app试图函数: myapp/views.py
from myapp.models import User
from .serializers import UserSerializer
from rest_framework import viewsets

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
  1. app路由: myapp/urls.py
from django.urls import path,include
from myapp import views
from rest_framework import routers

router = routers.DefaultRouter()
router.register(ruser, views.UserViewSet)

urlpatterns = [
    path(api/,include(router.urls))
]
  1. 启动项目访问: http://127.0.0.1:8000/myapp/api/

  1. API信息提交: http://127.0.0.1:8000/myapp/api/user/

  1. 接口信息概览
http://127.0.0.1:8000/myapp/api/user/   #列出所有数据
http://127.0.0.1:8000/myapp/api/user/1/   #对于指定数据进行更新,删除,查看操作

DRF序列化器

序列化与反序列化介绍

在日常开发中,会从别的API获取数据或者自己写API提供数据,数据格式一般都是采用JSON格式。这期间就会涉及两个专业术语:

  • **序列化:**将python对象转json,后端响应

  • **反序列化:**将json转为python对象, 后端处理数据需要转换成python对象

之前常用三种序列化方式:JSON

之前经常用json模式完成序列化与反序列化操作:

  • 序列化应用场景示例:用ORM查询数据,采用JSON格式API返回数据。
  • 反序列化应用场景示例:从别的API获取数据,在Python里处理。

之前常用三种序列化方式: Django内置Serializers模块

Serializers是Django内置的一个序列化器,可直接将Python对象转为JSON格式,但不支持反序列化

from django.core import serializers
obj = User.objects.all()
data = serializers.serialize(json, obj)

之前常用三种序列化方式: Django内置JsonResponse模块

JsonResponse模块自动将Python对象转为JSON对象并响应。

DRF序列化器

DRF中有一个serializers模块专门负责数据序列化,DRF提供的方案更先进、更高级别的序列化方案。

  • 序列化器支持三种类型:
    • **Serializer:**对Model(数据模型)进行序列化,需自定义字段映射。
    • **ModelSerializer:**对Model进行序列化,会自动生成字段和验证规则,默认还包含简单的create()和update()方法。
    • **HyperlinkedModelSerializer:**与ModelSerializer类似,只不过使用超链接来表示关系而不是主键ID。

Serializer用户查询接口

  1. 编写app序列化器文件: myapp/serializers.py
from rest_framework import serializers

class UserSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    name = serializers.CharField()
    city = serializers.CharField()
    sex = serializers.CharField()
    age = serializers.CharField()
  1. app视图函数: myapp/views.py
from rest_framework.views import APIView
from rest_framework.response import Response

class UserApiView(APIView):
    def get(self,request,id=None):
        #获取单条数据
        if id:
            user_obj = User.objects.get(id=id)
            user_serializers = UserSerializer(user_obj)
        else:
        #返回所有数据
            queryset = User.objects.all()
            user_serializers = UserSerializer(queryset,many=True)
        return Response(user_serializers.data)
  1. app路由: myapp/urls.py
from django.urls import re_path
from myapp import views
urlpatterns = [
    re_path(api/user/$,views.UserApiView.as_view()),
    re_path(api/user/(?P<pk>\\d+)/$,views.UserApiView.as_view()),
]
  1. 数据查看测试:

    a. http://127.0.0.1:8000/myapp/api/user/

​ b. 查看单条数据: http://127.0.0.1:8000/myapp/api/user/1/

Serializer用户创建接口

上述的配置不变,只需要变动视图和序列化

  1. app视图函数: myapp/views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from myapp.models import User
from .serializers import UserSerializer

class UserApiView(APIView):
    def get(self,request,id=None):
        #获取单条数据
        if id:
            user_obj = User.objects.get(id=id)
            user_serializers = UserSerializer(user_obj)
        else:
        #返回所有数据
            queryset = User.objects.all()
            user_serializers = UserSerializer(queryset,many=True)
        return Response(user_serializers.data)

    def post(self,request):
        #数据反序列化
        user_ser = UserSerializer(data=request.data)    #request.data是用户POST数据
        if user_ser.is_valid():
            #保存数据库
            user_ser.save()
            res = code: 200, msg: 创建用户成功
        else:
            res = code: 500, msg: 创建用户失败
        return Response(res)
  1. app序列化文件: myapp/serializers.py
from myapp.models import User
from rest_framework import serializers
class UserSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    name = serializers.CharField()
    city = serializers.CharField()
    sex = serializers.CharField()
    age = serializers.IntegerField()

    def create(self, validated_data):
        return User.objects.create(**validated_data)
  1. 创建数据测试: http://127.0.0.1:8000/myapp/api/user/

  1. 创建数据结果返回: http://127.0.0.1:8000/myapp/api/user/

Serializer用户更新和删除接口

  1. app视图函数: myapp/views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from myapp.models import User
from .serializers import UserSerializer
from rest_framework import viewsets

class UserApiView(APIView):
    def get(self,request,id=None):
        #获取单条数据
        if id:
            user_obj = User.objects.get(id=id)
            user_serializers = UserSerializer(user_obj)
        else:
        #返回所有数据
            queryset = User.objects.all()
            user_serializers = UserSerializer(queryset,many=True)
        return Response(user_serializers.data)

    def post(self,request):
        #数据反序列化
        user_ser = UserSerializer(data=request.data)    #request.data是用户POST数据
        if user_ser.is_valid():
            #保存数据库
            user_ser.save()
            res = code: 200, msg: 创建用户成功
        else:
            res = code: 500, msg: 创建用户失败
        return Response(res)

    def put(self,request,id=None):
        user_obj = User.objects.get(id=id)
        user_serializer = UserSerializer(instance=user_obj, data=request.data)
        if user_serializer.is_valid():
            user_serializer.save()
            res = code: 200, msg: 更新用户成功
        else:
            res = code: 500, msg: 更新用户失败
        return Response(res)
    
    def delete(self,request,id=None):
        user_obj = User.objects.get(id=id)
        user_obj.delete()
        res = code: 200, msg: 删除用户成功
        return Response(res)
  1. 序列化配置: myapp/serializers.py
from myapp.models import User
from rest_framework import serializers

class UserSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    name = serializers.CharField()
    city = serializers.CharField()
    sex = serializers.CharField()
    age = serializers.IntegerField()

    def create(self, validated_data):
        return User.objects.create(**validated_data)

    def update(self, instance, validated_data):
        return User.objects.filter(id=instance.id).update(**validated_data)
  1. 数据更新测试: http://127.0.0.1:8000/myapp/api/user/1/

  1. 状态查看:PUT之后查看

  1. 删除数据: http://127.0.0.1:8000/myapp/api/user/3/

  2. 查看结果: http://127.0.0.1:8000/myapp/api/user/

错误返回值优化

  • 在数据校验时候传入这个配置即可捕获异常,异常状态码是400: raise_exception=True

  • 需要修改app的视图函数: myapp/views.py

from myapp.models import User
from .serializers import UserSerializer
from rest_framework import viewsets

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer


from rest_framework.views import APIView
from rest_framework.response import Response

class UserApiView(APIView):
    def get(self,request,id=None):
        #获取单条数据
        if id:
            user_obj = User.objects.get(id=id)
            user_serializers = UserSerializer(user_obj)
        else:
        #返回所有数据
            queryset = User.objects.all()
            user_serializers = UserSerializer(queryset,many=True)
        return Response(user_serializers.data)

    def post(self,request):
        #数据反序列化
        user_serializer = UserSerializer(data=request.data)    #request.data是用户POST数据
        user_serializer.is_valid(raise_exception=True)
        user_serializer.save()
        res = code: 200, msg: 创建用户成功
        return Response(res)

    def put(self,request,id=None):
        user_obj = User.objects.get(id=id)
        user_serializer = UserSerializer(instance=user_obj, data=request.data)
        user_serializer.is_valid(raise_exception=True)
        user_serializer.save()
        res = code: 200, msg: 创建用户成功
        return Response(res)

    def delete(self,request,id=None):
        user_obj = User.objects.get(id=id)
        user_obj.delete()
        res = code: 200, msg: 删除用户成功
        return Response(res)
  • 更新和创建数据测试

DRF序列化器: 序列化器参数

  • 序列化器工作流程:

    • 序列化(读数据:视图里通过ORM从数据库获取数据查询集对象 -> 数据传入序列化器-> 序列化器将数据进行序列化 -> 调用序列化器的.data获取数据 -> 响应返回前端
    • 反序列化(写数据):视图获取前端提交的数据 -> 数据传入序列化器 -> 调用序列化器的.is_valid方法进行效验 -> 调用序列化器的.save()方法保存数据
  • 序列化器常用方法与属性:

    • serializer.is_valid():调用序列化器验证是否通过,传入raise_exception=True可以在验证失败时由DRF响应400异常。
    • serializer.errors:获取反序列化器验证的错误信息
    • serializer.data:获取序列化器返回的数据
    • serializer.save():将验证通过的数据保存到数据库(ORM操作)
  • 常用参数

  • 通用参数

DRF序列化器:扩展验证规则

如果常用参数无法满足验证要求时,可通过钩子方法扩展验证规则。

  • 局部钩子:validate_字段名(self, 字段值)
  • 全局钩子:validate(self, 所有校验的数据字典)

以上是关于2. DRF入门的主要内容,如果未能解决你的问题,请参考以下文章

DRF入门规范

django-rest-framework(drf入门)

drf入门规范

drf 整体流程

drf入门规范序列化器组件视图组件请求与响应

ExtJs 4:如何在一个请求中发送所有修改、新和删除的记录?