zoukankan      html  css  js  c++  java
  • django restframework 教程之Serialization(序列化)

    介绍

    本教程将会通过创建一个简单的粘贴代码项目,突出显示WebAPI,过程中,会介绍组成REST框架的各种组件,让你全面了解如何配合使用。

    环境设置

    建议使用virtualenv建立新的虚拟环境,确保本项目所依赖的任何包和其他环境保持隔离

    virtualenv env
    source env/bin/activate
    

    现在在新的虚拟环境中安装必须的包

    pip install django
    pip install djangorestframework
    pip install pygments  #代码高亮使用
    

    创建项目

    我们将创建名为tutorial的项目,在项目中创建名为snippets的app

    django-admin.py startproject tutorial
    cd tutorial
    python manage.py startapp snippets
    
    

    最后我们需要在settings.pyINSTALLED_APPS配置里注册我们的snippetsapp和rest_frameworkapp

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

    注意:如果使用的django版本低于1.9,直接使用snippets 来代替snippets.apps.SnippetsConfig即可

    创建model

    下面创建snippets所使用的数据库表用来存储代码

    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
    

    创建序列化的类

    首先我们需要为api提供序列化和反序列化的方法,将snippet实例转为json等方式呈现数据,我们可以使用Serializer达到这一目的, Serializer和django forms十分相似. 我们在snippetapp下新建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):
            """
            新建Snippet实例
            """
            return Snippet.objects.create(**validated_data)
    
        def update(self, instance, validated_data):
            """
            更新Snippet示例
            """
            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
    

    serializer的首先定义了序列化和反序列化的字段,其次create()update()方法定义了当调用serializer.save()时如何对实例进行创建或修改
    serializer和django的form非常类似,而且包括一些类似的验证字段的方法,如required,max_lengthanddefault.

    使用Serializers

    我们使用django的shell 环境来简单的测试Serializers

    创建两个snippet实例

    python3 manage.py 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"
    ')
    >>> snippet.save()
    >>> snippet2 = Snippet(code='print "hello, world"
    ')
    >>> snippet2.save()
    

    序列化其中一个实例

    >>> serializer = SnippetSerializer(snippet2)
    >>> serializer.data
    {'linenos': False, 'id': 2, 'code': 'print "hello, world"
    ', 'language': 'python', 'style': 'friendly', 'title': ''}
    

    我们已经将snippet2序列化为一个python的基本数据类型,现在我们生成json数据

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

    反序列化更简单,首先将stream转为python基本类型

    >>> from django.utils.six import BytesIO
    >>> stream = BytesIO(content)
    >>> data = JSONParser().parse(stream)
    >>> data
    {'linenos': False, 'id': 2, 'code': 'print "hello, world"
    ', 'language': 'python', 'style': 'friendly', 'title': ''}
    

    然后,我们将其转换为snippet实例

    >>> 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()
    <Snippet: Snippet object>
    
    

    我们也可以序列化querysets对象来代替model instances,因此在序列化的时候需要添加many=True参数

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

    使用ModelSerializers

    我们的SnippetSerializer类很多信息和Snippet model中是重复的,为了保证我们代码的简洁,减少重复代码,类似于django的提供的formmodelform,REST framework也提供了Serializerand ModelSerializer
    下面使用ModelSerializer重构我们的serializer,重新打开serializers.py,使用下面代码替换掉SnippetSerializer

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

    serializers有一个不错的属性是,可以通过print函数来打印它 表示检查序列化实例中的所有字段

    >>> from snippets.serializers import SnippetSerializer
    >>> serializer = SnippetSerializer()
    >>> print(repr(serializer))
    

    重要的是要记住 ModelSerializer 不做任何格外的配置,它只是创建序列化类的快捷方式:

    • 根据model里的字段自动定义字段集
    • 简单的实现 create() and update() 方法

    在django 视图中使用我们的Serializer

    让我们看看我们如何使用我们新的Serializer类编写一些API视图。目前我们不使用任何REST框架的其他功能,我们只是将视图写为常规Django视图。
    我们将开始通过创建一个HttpResponse子类用来返回任何形式的数据,如json;
    编辑views.py

    from django.http import HttpResponse
    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
    
    class JSONResponse(HttpResponse):
        """
        An HttpResponse that renders its content into JSON.
        """
        def __init__(self, data, **kwargs):
            content = JSONRenderer().render(data)
            kwargs['content_type'] = 'application/json'
            super(JSONResponse, self).__init__(content, **kwargs)
    
    
    @csrf_exempt
    def snippet_list(request):
        """
        列出所有的实例,或创建一个新的实例.
        """
        if request.method == 'GET':
            snippets = Snippet.objects.all()
            serializer = SnippetSerializer(snippets, many=True)
            return JSONResponse(serializer.data)
    
        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)
    

    注意我们在post测试的时候无法获取到Django的csrf token,所以使用@csrf_exempt将此视图排除,不在检查csrf token
    我们将还需要一个与单个代码段对应的视图,并且可以用来检索、更新和删除代码段

    @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信息,在snippetapp下,新建urls.py

    from django.conf.urls import url
    from snippets import views
    
    urlpatterns = [
        url(r'^snippets/$', views.snippet_list),
        url(r'^snippets/(?P<pk>[0-9]+)/$', views.snippet_detail),
    ]
    

    我们也需要在tutorial项目的urls.py下将snippetapp的url配置加载进去

    from django.conf.urls import url, include
    
    urlpatterns = [
        url(r'^', include('snippets.urls')),
    ]
    

    尝试测试我们的web api

    启动我们的django server

    python manage.py runserver
    
    Performing system checks...
    
    System check identified no issues (0 silenced).
    February 04, 2017 - 08:38:55
    Django version 1.10, using settings 'tutorial.settings'
    Starting development server at http://127.0.0.1:8000/
    Quit the server with CONTROL-C.
    

    最后使用curl 进行测试

    curl -s http://127.0.0.1:8000/snippets/ | jq .
    [
      {
        "id": 1,
        "title": "",
        "code": "foo = "bar"
    ",
        "linenos": false,
        "language": "python",
        "style": "friendly"
      },
      {
        "id": 2,
        "title": "",
        "code": "print "hello, world"
    ",
        "linenos": false,
        "language": "python",
        "style": "friendly"
      },
      {
        "id": 3,
        "title": "",
        "code": "print "hello, world"",
        "linenos": false,
        "language": "python",
        "style": "friendly"
      }
    ]
    
    

    也可以指定id进行查询

    curl -s http://127.0.0.1:8000/snippets/1/ | jq .
    {
      "id": 1,
      "title": "",
      "code": "foo = "bar"
    ",
      "linenos": false,
      "language": "python",
      "style": "friendly"
    }
    

    源文参考:http://www.django-rest-framework.org/tutorial/1-serialization/#testing-our-first-attempt-at-a-web-api

  • 相关阅读:
    Hello World!
    Nginx加权轮询算法
    git常用命令
    linux命令
    sql 表值函数与标量值函数
    数据查询和操纵时连接的打开状态
    插入一条和上一条数据关联的数据
    C# 输出24小时格式时间
    c#中用sql存储过程
    AndroidManifest.xml文件解析
  • 原文地址:https://www.cnblogs.com/pycode/p/6365905.html
Copyright © 2011-2022 走看看