Django Rest FrameWork (一)序列化

建立一个新的 Django 开发环境:

  1. 使用 virtualenv 创建一个新的虚拟环境。

    mkdir ~/env/
    virtualenv ~/env/tutorial
    source ~/env/tutorial/bin/activate
    

  2. 接着,在虚拟环境内部安装我们所需要的包

    pip install django
    pip install djangorestframework
    pip install pygments
    

  3. 创建一个 django 项目

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

  4. 为了方便这里使用 sqlite3 作为数据库,并且编辑 tutorial/setting.py 文件。

            DATABASES = {
            'default':{
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': 'tmp.db',
                'USER': '',
                'PASSWORD': '',
                'HOST': '',
                'PORT': '',
            }
        }
    

  5. 同时,我们需要将 snippets app 和 rest_framewokr app 加载到 INSTALLED_APPS。

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

  6. 需要在 项目根目录下的 urls.py 增加如下配置:

    urlpatterns += [
            url(r'^', include('snippets.urls')),
    ]
    


创建一个 models

  1. 创建一个简单的 Snippet model. 修改 snippets 目录下 models.py 文件
from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles

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

class Snippet(models.Model):
        created = models.DateTimeField(auto_now_add=True)
        title = models.CharField(max_length=100, 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',)

接着,在数据库中生成 snippet 表

python manage.py makemigrations
python manage.py migrate

建立一个 Serializer 类

  1. 在 snippet 文件夹中创建一个 serializers.py 文件并且添加如下代码:
from django.forms import widgets
from rest_framework import serializers
from snippets import models

class SnippetSerializer(serializers.Serializer):
        pk = serializers.Field()  # Note: `Field` is an untyped read-only field.
        title = serializers.CharField(required=False,
                                      max_length=100)
        code = serializers.CharField(widget=widgets.Textarea,
                                     max_length=100000)
        linenos = serializers.BooleanField(required=False)
        language = serializers.ChoiceField(choices=models.LANGUAGE_CHOICES,
                                           default='python')
        style = serializers.ChoiceField(choices=models.STYLE_CHOICES,
                                        default='friendly')

        def restore_object(self, attrs, instance=None):
            """
            Create or update a new snippet instance.
            """
            if instance:
                # Update existing instance
                instance.title = attrs['title']
                instance.code = attrs['code']
                instance.linenos = attrs['linenos']
                instance.language = attrs['language']
                instance.style = attrs['style']
                return instance

            # Create new instance
            return models.Snippet(**attrs)
  1. 在 Django shell 中应用 Serializers
     $ python 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='print "hello, world"\n')
snippet.save()

将数据序列化成一个实例

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

最后将实例转换成 json 格式

content = JSONRenderer().render(serializer.data)

content
# '{"pk": 1, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false, "language": "python", "style": "friendly"}'