Django REST framework 教程(2)—— 序列化

参考自 Django REST framework 官方文档 ,权作笔记。

一、环境搭建

通过 Python3 内置的 venv 模块创建虚拟开发环境:

$ python3 -m venv env    # 创建名为 env 的虚拟环境
$ source env/bin/activate    # 启用虚拟环境
# env\Scripts\activate    Windows 系统启用虚拟环境

安装依赖库:

$ pip install django
$ pip install djangorestframework
$ pip install pygments    # We'll be using this for the code highlighting
初始化项目
$ django-admin startproject tutorial
$ cd tutorial
$ python manage.py startapp snippets

编辑 tutorial/tutorial/settings.py 配置文件,将 rest_frameworksnippets APP 添加到 INSTALLED_APPS 选项中。

INSTALLED_APPS = [
    ...
    'rest_framework',
    'snippets.apps.SnippetsConfig',
]

二、创建模型

编辑 tutorial/snippets/models.py 文件创建数据模型。内容如下:

from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles

LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
STYLE_CHOICES = sorted([(item, item) for item in get_all_styles()])


class Snippet(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default='')
    code = models.TextField()
    linenos = models.BooleanField(default=False)
    language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
    style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)

    class Meta:
        ordering = ['created']

使用以下命令完成数据库迁移操作:

$ python manage.py makemigrations snippets
$ python manage.py migrate

三、创建序列化器

序列化是指将 Web API 提供的后台数据已特定的形式(如 json 格式)展示给用户,方便前端程序调用。

以下代码反映了一个序列化器的基本逻辑。编辑 tutorial/snippets/serializers.py 文件,内容如下:

from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES


class SnippetSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    title = serializers.CharField(required=False, allow_blank=True, max_length=100)
    code = serializers.CharField(style={'base_template': 'textarea.html'})
    linenos = serializers.BooleanField(required=False)
    language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python')
    style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')

    def create(self, validated_data):
        """
        Create and return a new `Snippet` instance, given the validated data.
        """
        return Snippet.objects.create(**validated_data)

    def update(self, instance, validated_data):
        """
        Update and return an existing `Snippet` instance, given the validated data.
        """
        instance.title = validated_data.get('title', instance.title)
        instance.code = validated_data.get('code', instance.code)
        instance.linenos = validated_data.get('linenos', instance.linenos)
        instance.language = validated_data.get('language', instance.language)
        instance.style = validated_data.get('style', instance.style)
        instance.save()
        return instance
ModelSerializer

Django REST framework 框架通过 serializers 中的某些类对序列化器的逻辑功能做了封装与抽象,因此可以通过这些类完成与上面代码同样的需求,同时代码的冗余度大大降低。
可以将 tutorial/snippets/serializers.py 文件改为如下版本:

from rest_framework import serializers
from snippets.models import Snippet

class SnippetSerializer(serializers.ModelSerializer):
    class Meta:
        model = Snippet
        fields = ['id', 'title', 'code', 'linenos', 'language', 'style']

四、Django Shell 操作 Serializer

运行以下命令进入 Django Shell:$ python manage.py shell

通过 Snippet 模型创建数据纪录:

>>> from snippets.models import Snippet
>>> from snippets.serializers import SnippetSerializer
>>> from rest_framework.renderers import JSONRenderer
>>> from rest_framework.parsers import JSONParser
>>> snippet = Snippet(code='foo = "bar"\n')
>>> snippet.save()
>>> snippet = Snippet(code='print("hello, world")\n')
>>> snippet.save()

序列化数据对象并以 JSON 的形式展示:

>>> serializer = SnippetSerializer(snippet)
>>> serializer.data
{'id': 2, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}
>>> content = JSONRenderer().render(serializer.data)
>>> content
b'{"id":2,"title":"","code":"print(\\"hello, world\\")\\n","linenos":false,"language":"python","style":"friendly"}'

反序列化:

>>> import io
>>> stream = io.BytesIO(content)
>>> data = JSONParser().parse(stream)
>>> serializer = SnippetSerializer(data=data)
>>> serializer.is_valid()
True
>>> serializer.validated_data
OrderedDict([('title', ''), ('code', 'print("hello, world")'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])
>>> serializer.save()

序列化多个模型实例:

>>> serializer = SnippetSerializer(Snippet.objects.all(), many=True)
>>> serializer.data
[OrderedDict([('id', 1), ('title', ''), ('code', 'foo = "bar"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 2), ('title', ''), ('code', 'print("hello, world")\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 3), ('title', ''), ('code', 'print("hello, world")'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])]

五、视图

编辑 tutorial/snippets/views.py 文件,创建 snippet_listsnippet_detail 两个视图函数,并添加上对 GETPOST 等请求的响应逻辑。内容如下:

from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer


@csrf_exempt
def snippet_list(request):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        snippets = Snippet.objects.all()
        serializer = SnippetSerializer(snippets, many=True)
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = SnippetSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)


@csrf_exempt
def snippet_detail(request, pk):
    """
    Retrieve, update or delete a code snippet.
    """
    try:
        snippet = Snippet.objects.get(pk=pk)
    except Snippet.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = SnippetSerializer(snippet)
        return JsonResponse(serializer.data)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        serializer = SnippetSerializer(snippet, data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data)
        return JsonResponse(serializer.errors, status=400)

    elif request.method == 'DELETE':
        snippet.delete()
        return HttpResponse(status=204)

六、路由配置

编辑 tutorial/snippets/urls.py 文件,完成视图与 URL 路径的关联:

from django.urls import path
from snippets import views

urlpatterns = [
    path('snippets/', views.snippet_list),
    path('snippets//', views.snippet_detail),
]

tutorial/tutorial/urls.py 配置文件中引入 snippets 应用的路由配置:

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

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

七、测试

运行 $ python manage.py runserver 命令开启测试服务,使用 httpie 工具对 API 进行访问测试,结果如下:

GET 方法获取数据:

$ http -b 172.20.19.76:8000/snippets/
[
    {
        "code": "foo = \"bar\"\n",
        "id": 1,
        "language": "python",
        "linenos": false,
        "style": "friendly",
        "title": ""
    },
    {
        "code": "print(\"hello, world\")\n",
        "id": 2,
        "language": "python",
        "linenos": false,
        "style": "friendly",
        "title": ""
    }
]

POST 方法添加新的数据:

$ http -b POST 172.20.19.76:8000/snippets/ code="a = 1\nb = 2\nprint(a + b)"
{
    "code": "a = 1\\nb = 2\\nprint(a + b)",
    "id": 4,
    "language": "python",
    "linenos": false,
    "style": "friendly",
    "title": ""
}

你可能感兴趣的:(Django REST framework 教程(2)—— 序列化)