django rest-farme-work 的使用(2)

serialization (序列化)

本测试项目例子地址为:

tomchristie/rest-framework-tutorial

开始构建一个新的程序

创建一个新的环境

virtualenv env
source env/bin/activate

安装相应的包

pip install django
pip install djangorestframework
pip install pygments  # We'll be using this for the code highlighting(代码高亮)

创建一个项目

cd ~
django-admin.py startproject tutorial
cd tutorial

建立一个App

python manage.py startapp snippets

在settings 文件中添加下配置

   
    'rest_framework',
    'snippets.apps.SnippetsConfig',

在 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。我们可以通过声明与Django的表单非常相似的序列化器来实现这一点。在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

序列化器类的第一部分定义了序列化/反序列化的字段。该create()和update()方法定义实例如何完全成熟的创建或修改时调用serializer.save()

甲串行类非常类似于一个Django Form类,并且包括关于各个字段类似的验证标记,如required,max_length和default。

字段标志还可以控制在某些情况下应该如何显示序列化程序,例如在呈现为HTML时。{'base_template': 'textarea.html'}上面的标志等同于widget=widgets.Textarea在Django Form类上使用。这对于控制如何显示可浏览的API特别有用,正如我们将在本教程后面看到的。

我们实际上也可以通过使用这个ModelSerializer类节省一些时间,我们稍后会看到,但现在我们将保持我们的序列化器定义清晰。

测试序列化类

在我们继续之前,我们将熟悉使用我们的新Serializer类。我们来看看Django shell。


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()

我们来看看序列化其中的一个实例。


serializer = SnippetSerializer(snippet)
serializer.data
# {'id': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}

在前面上,我们已经将模型实例转换为Python本地数据类型。为了完成序列化过程,我们将数据渲染到json

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

反序列化

from django.utils.six import BytesIO

stream = BytesIO(content)
data = JSONParser().parse(stream)

将本地的数据类型恢复填充到数据库


serializer = SnippetSerializer(data=data)
serializer.is_valid()
# True
serializer.validated_data
# OrderedDict([('title', ''), ('code', 'print "hello, world"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])
serializer.save()
# 

注意API与表单的工作方式相似。当我们开始编写使用我们的序列化器的视图时,相似性应该变得更加明显。

我们也可以序列化查询集而不是模型实例。为此,我们只需many=True在序列化参数中添加一个标志即可

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

使用ModelSerializer

前面我们SnippetSerializer类复制Snippet模型中包含的大量信息。如果我们可以保持我们的代码更加简洁。

让我们看看使用ModelSerializer类重构我们的序列化程序。snippets/serializers.py再次打开文件,把SnippetSerializer类重新定义,如下


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

记住ModelSerializer类不要做任何特别的事情是很重要的,它们只是创建序列化类的一个捷径。

  • 自动确定的一组字段。
  • 简单的默认实现create()和update()方法。

使用我们的序列化程序编写常规的Django视图

编辑snippets/views.py文件,并添加以下内容。


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
##ddvim

@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)


配置url


from django.conf.urls import url, include
from snippets import views
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    url(r'^snippets/$',views.snippet_list),
    url(r'^snippets/(?P[0-9]+)/$',views.snippet_detail),

]

安装调试工具

pip install httpie

测试

http http://127.0.0.1:8000/snippets/

HTTP/1.1 200 OK
...
[
  {
    "id": 1,
    "title": "",
    "code": "foo = \"bar\"\n",
    "linenos": false,
    "language": "python",
    "style": "friendly"
  },
  {
    "id": 2,
    "title": "",
    "code": "print \"hello, world\"\n",
    "linenos": false,
    "language": "python",
    "style": "friendly"
  }
]

http http://127.0.0.1:8000/snippets/2/

HTTP/1.1 200 OK
...
{
  "id": 2,
  "title": "",
  "code": "print \"hello, world\"\n",
  "linenos": false,
  "language": "python",
  "style": "friendly"
}

你可能感兴趣的:(django rest-farme-work 的使用(2))