闪修服务端04-首页轮播图接口-RDF序列化与反序列化

Django的序列化和反序列化

序列化:将程序中的一个数据结构类型转换为其他格式(字典、JSON、XML等),例如将Django中的模型类对象装换为JSON字符串,这个转换过程我们称为序列化。

反序列化:将其他格式(字典、JSON、XML等)转换为程序中的数据,例如将JSON字符串转换为Django中的模型类对象,这个过程我们称为反序列化。

在开发REST API接口时,我们在视图中需要做的最核心的事是:

  • 将数据库数据序列化为前端所需要的格式,并返回
  • 将前端发送的数据反序列化为模型类对象,并保存到数据库中

Django REST framework 简介

https://www.django-rest-framework.org/

Django REST framework是一个建立在Django基础之上的Web应用开发框架,可以快速的开发REST API接口应用。

在REST framework中,提供了序列化器Serialzier的定义,可以帮助我们简化序列化与反序列化的过程

开始下面例子前,建议先阅读官网教程-Tutorial 1: Serialization

首页轮播图接口开发

1. 数据库设计 sxapp/models.py

# 首页轮播图控制表
class Swiper(models.Model):
    title = models.CharField('图片的描述', max_length=3000, null=True, blank=True)
    url = models.CharField('图片外链', max_length=3000)
    is_show = models.CharField('是否启用', max_length=3000, null=True, blank=True)  # '1'为启用,'0'为不启用

    class Meta:
        ordering = ['id']
        verbose_name = '首页轮播图控制表'
        verbose_name_plural = '首页轮播图控制表'

初始化数据库

python manage.py makemigrations
python manage.py migrate

2. 编写序列化类 sxapp/serializers.py

from rest_framework import serializers

from sxapp.models import Swiper


class SwiperSer(serializers.ModelSerializer):
    class Meta:
        model = Swiper  # 指定数据库model
        fields = "__all__" # 默认序列化所有的字段
        # fields = ['id', 'title','url','is_show'] # 指定序列化字段
        # exclude = ('id', 'is_show') # 排除部分字段

3. 首页轮播图接口视图代码 sxapp/views.py

from django.http import JsonResponse
from sxapp.models import Swiper
from sxapp.serializers import SwiperSer
from django.views.decorators.csrf import csrf_exempt


@csrf_exempt
def swiper_view(request):
    """ 首页轮播图"""
    if request.method == "GET":
        # 序列化,将数据库数据序列化为前端所需要的格式,并返回
        swiper_set = Swiper.objects.all()
        serializer = SwiperSer(swiper_set, many=True)  # 序列化,当序列化queryset时,注意传入参数many=True
        return JsonResponse(serializer.data, safe=False)
    if request.method == "POST":
        # 反序列化,将前端发送的数据反序列化为模型类对象,并保存到数据库中
        # 这块代码,仅仅是因为演示反序列化过程
        # 通过form表单提交
        verify_data = SwiperSer(data=request.POST)
        if verify_data.is_valid():
            verify_data.save()
            return JsonResponse({"message": "create some data!", "data": request.POST})
        else:
            return JsonResponse(verify_data.errors)

4. 添加路由 sx_backend/urls.py

from django.contrib import admin
from django.urls import path

from sxapp.views import swiper_view

urlpatterns = [
    path('admin/', admin.site.urls),
    path('swiper/',swiper_view), # 轮播图表的数据接口
]

测试轮播图接口

  • 通过post,插入3张轮播图
    curl -X POST -d "title=p1&url=https://cdn.uviewui.com/uview/swiper/swiper1.png&is_show=1" http://localhost:8000/swiper/
    curl -X POST -d "title=p2&url=https://cdn.uviewui.com/uview/swiper/swiper2.png&is_show=1" http://localhost:8000/swiper/
    curl -X POST -d "title=p3&url=https://cdn.uviewui.com/uview/swiper/swiper3.png&is_show=1" http://localhost:8000/swiper/
  • 通过get,返回轮播图列表
    curl  http://localhost:8000/swiper/
    [{
    	"id": 1,
    	"title": "p1",
    	"url": "https://cdn.uviewui.com/uview/swiper/swiper1.png",
    	"is_show": "1"
    }, {
    	"id": 2,
    	"title": "p2",
    	"url": "https://cdn.uviewui.com/uview/swiper/swiper2.png",
    	"is_show": "1"
    }, {
    	"id": 3,
    	"title": "p3",
    	"url": "https://cdn.uviewui.com/uview/swiper/swiper3.png",
    	"is_show": "1"
    }]

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。
My Show My Code