Django REST framework 学习纪要 Tutorial 1 Serialization

依赖

  • Python 3.6.3 [ Python (2.7, 3.2, 3.3, 3.4, 3.5, 3.6) 都可以 ]
  • Django 1.11.7 [ Django (1.10, 1.11, 2.0 alpha) 都可以 ]

安装、创建并配置虚拟环境

  • 安装虚拟环境
    Python版本管理工具 Pyenv的安装与使用

  • 创建虚拟环境

mkdir django_rest_framework && cd django_rest_framework
pyenv virtualenv 3.6.3 django_rest_framework
pyenv local django_rest_framework
  • 安装相关包
pip install django djangorestframework
pip install pygments  # 项目中会用到,提供代码高亮功能

Django项目初始化

  • 创建tutorial项目与snippets应用
django-admin startproject tutorial
cd tutorial/

python manage.py startapp snippets
  • snippets应用和rest_framework添加进settings.pyINSTALLED_APPS (如果Django版本小于1.9,则需要将snippets.apps.SnippetsConfig替换为snippets)
INSTALLED_APPS = (
    ...
    'rest_framework',
    'snippets.apps.SnippetsConfig',
)

创建Model

我们需要创建一个Snippet模型来存储代码片段。

  • 修改snippets/models.py文件
from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles

# 提取出了pygments支持的所有语言的词法分析程序
LEXERS = [item for item in get_all_lexers() if item[1]]
# 提取出了pygments支持的所有语言列表
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
# 提取出了pygments支持的所有格式化风格列表
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

创建Serializer类

  • snippets文件夹内创建serializers.py文件
from rest_framework import serializers
from snippets.models import LANGUAGE_CHOICES
from snippets.models import Snippet
from snippets.models import 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

使用Serializers类

  • 打开Django shell
python manage.py shell
  • 创建两个Serializers对象
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()

序列化

  • 序列化一个对象
In [11]: serializer = SnippetSerializer(snippet)

In [12]: serializer.data
Out[12]: 
ReturnDict([('id', 2),
            ('title', ''),
            ('code', 'print "hello, world"\n'),
            ('linenos', False),
            ('language', 'python'),
            ('style', 'friendly')])
  • 将data数据转换为json
In [13]: content = JSONRenderer().render(serializer.data)

In [14]: content
Out[14]: b'{"id":2,"title":"","code":"print \\"hello, world\\"\\n","linenos":false,"language":"python","style":"friendly"}'

反序列化

  • 将JSON数据转为Python原生数据类型(字典)
In [15]: from django.utils.six import BytesIO

In [16]: stream = BytesIO(content)

In [17]: data = JSONParser().parse(stream)

In [18]: data
Out[18]: 
{'code': 'print "hello, world"\n',
 'id': 2,
 'language': 'python',
 'linenos': False,
 'style': 'friendly',
 'title': ''}
  • 将Python原生数据类型(字典)转换为对象
In [19]: serializer = SnippetSerializer(data=data)

In [20]: serializer.is_valid()
Out[20]: True

In [21]: serializer.validated_data
Out[21]: 
OrderedDict([('title', ''),
             ('code', 'print "hello, world"'),
             ('linenos', False),
             ('language', 'python'),
             ('style', 'friendly')])

In [22]: serializer.save()
Out[22]: 
  • 可以序列化查询集,只需要添加many=True参数
In [23]: serializer = SnippetSerializer(Snippet.objects.all(), many=True)

In [24]: serializer.data
Out[24]: [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')])]

使用ModelSerializer

刚才定义的SnippetSerializer类中的类中有很多是和之前在models.py定义的内容重复,其实我们还可以使SnippetSerializer类继承于ModelSerializer,来减少这种重复定义。

  • SnippetSerializer类重新定义,为如下内容:
class SnippetSerializer(serializers.ModelSerializer):
    class Meta:
        model = Snippet
        fields = ('id', 'title', 'code', 'linenos', 'language', 'style')
  • 打开Django shell
python manage.py shell
  • 查看SnippetSerializer
In [1]: from snippets.serializers import SnippetSerializer

In [2]: serializer = SnippetSerializer()

In [3]: print(repr(serializer))
SnippetSerializer():
    id = IntegerField(label='ID', read_only=True)
    title = CharField(allow_blank=True, max_length=100, required=False)
    code = CharField(style={'base_template': 'textarea.html'})
    linenos = BooleanField(required=False)
    language = ChoiceField(choices=[('abap', 'ABAP'), ('abnf', 'ABNF'), ('ada', 'Ada'), ('adl', 'ADL'), ('agda', 'Agda'), ('aheui', 'Aheui'), ('ahk', 'autohotkey'),
 ...

至此我们发现,继承于ModelSerializer类,有两个非常大的作用:

  1. 不用重复去定义类属性
  2. 自动拥有create()update()方法

Serializer在Django views内的简单运用

  • 此处未使用REST framework的其它特性,仅使用常规的Django views
  • 此处的写法有很多漏洞,仅作为教程中测试展示使用,不能直接应用于生产环境

配置views

打开snippets/views.py

  • 导入相关包
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
  • 创建一个返回所有对象和对象增功能的API
@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)
  • 创建一个对象查、改、删功能的API
@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)

配置urls

  • 创建snippets/urls.py
from django.conf.urls import url
from snippets import views

urlpatterns = [
    url(r'^snippets/$', views.snippet_list),
    url(r'^snippets/(?P[0-9]+)/$', views.snippet_detail),
]
  • 配置项目根urls.py
from django.conf.urls import url
from django.conf.urls import include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('snippets.urls')),
]

测试接口

  • 启动服务
(django_rest_framework) [root@localhost tutorial]# python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
November 20, 2017 - 23:01:29
Django version 1.11.7, using settings 'tutorial.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
  • 打开另一个shell窗口

  • 安装httpie包,用于模拟http请求

pip install httpie
  • 发送请求,获取所有snippets对象
(django_rest_framework) [root@localhost tutorial]# http http://127.0.0.1:8000/snippets/
HTTP/1.0 200 OK
Content-Length: 352
Content-Type: application/json
Date: Mon, 20 Nov 2017 15:03:10 GMT
Server: WSGIServer/0.2 CPython/3.6.3
X-Frame-Options: SAMEORIGIN

[
    {
        "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": ""
    },
]
  • 发送请求,获取主键为2的snippets对象
(django_rest_framework) [root@localhost tutorial]# http http://127.0.0.1:8000/snippets/2/
HTTP/1.0 200 OK
Content-Length: 119
Content-Type: application/json
Date: Mon, 20 Nov 2017 15:03:17 GMT
Server: WSGIServer/0.2 CPython/3.6.3
X-Frame-Options: SAMEORIGIN

{
    "code": "print \"hello, world\"\n",
    "id": 2,
    "language": "python",
    "linenos": false,
    "style": "friendly",
    "title": ""
}

关于

本人是初学Django REST framework,Django REST framework 学习纪要系列文章是我从官网文档学习后的初步消化成果,如有错误,欢迎指正。

学习用代码Github仓库:shelmingsong/django_rest_framework

本文参考的官网文档:Tutorial 1: Serialization

博客更新地址

  • 宋明耀的博客 [ 第一时间更新 ]
  • 知乎专栏 Python Cookbook
  • 流月0的文章

你可能感兴趣的:(Django REST framework 学习纪要 Tutorial 1 Serialization)