serialization (序列化)
本測試項(xiàng)目例子地址為:
tomchristie/rest-framework-tutorial
開始構(gòu)建一個新的程序
創(chuàng)建一個新的環(huán)境
virtualenv env
source env/bin/activate
安裝相應(yīng)的包
pip install django
pip install djangorestframework
pip install pygments # We'll be using this for the code highlighting(代碼高亮)
創(chuàng)建一個項(xiàng)目
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',)
我們還需要為我們的片段模型創(chuàng)建初始遷移备蚓,并首次同步數(shù)據(jù)庫课蔬。
python manage.py makemigrations snippets
python manage.py migrate
創(chuàng)建一個序列化類
我們需要開始使用Web API的第一件事就是提供一種將代碼片段實(shí)例序列化和反序列化為表示形式的方法json。我們可以通過聲明與Django的表單非常相似的序列化器來實(shí)現(xiàn)這一點(diǎn)郊尝。在snippets名為的目錄中創(chuàng)建一個文件serializers.py并添加以下內(nèi)容二跋。
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()方法定義實(shí)例如何完全成熟的創(chuàng)建或修改時調(diào)用serializer.save()
甲串行類非常類似于一個Django Form類流昏,并且包括關(guān)于各個字段類似的驗(yàn)證標(biāo)記扎即,如required镀首,max_length和default坟比。
字段標(biāo)志還可以控制在某些情況下應(yīng)該如何顯示序列化程序,例如在呈現(xiàn)為HTML時芥丧。{'base_template': 'textarea.html'}上面的標(biāo)志等同于widget=widgets.Textarea在Django Form類上使用刁绒。這對于控制如何顯示可瀏覽的API特別有用襟锐,正如我們將在本教程后面看到的。
我們實(shí)際上也可以通過使用這個ModelSerializer類節(jié)省一些時間膛锭,我們稍后會看到粮坞,但現(xiàn)在我們將保持我們的序列化器定義清晰。
測試序列化類
在我們繼續(xù)之前初狰,我們將熟悉使用我們的新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()
我們來看看序列化其中的一個實(shí)例奢入。
serializer = SnippetSerializer(snippet)
serializer.data
# {'id': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}
在前面上筝闹,我們已經(jīng)將模型實(shí)例轉(zhuǎn)換為Python本地?cái)?shù)據(jù)類型。為了完成序列化過程腥光,我們將數(shù)據(jù)渲染到j(luò)son
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)
將本地的數(shù)據(jù)類型恢復(fù)填充到數(shù)據(jù)庫
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()
# <Snippet: Snippet object>
注意API與表單的工作方式相似关顷。當(dāng)我們開始編寫使用我們的序列化器的視圖時,相似性應(yīng)該變得更加明顯武福。
我們也可以序列化查詢集而不是模型實(shí)例议双。為此,我們只需many=True在序列化參數(shù)中添加一個標(biāo)志即可
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類復(fù)制Snippet模型中包含的大量信息捉片。如果我們可以保持我們的代碼更加簡潔平痰。
讓我們看看使用ModelSerializer類重構(gòu)我們的序列化程序。snippets/serializers.py再次打開文件伍纫,把SnippetSerializer類重新定義宗雇,如下
class SnippetSerializer(serializers.ModelSerializer):
class Meta:
model = Snippet
fields = ('id', 'title', 'code', 'linenos', 'language', 'style')
記住ModelSerializer類不要做任何特別的事情是很重要的,它們只是創(chuàng)建序列化類的一個捷徑莹规。
- 自動確定的一組字段赔蒲。
- 簡單的默認(rèn)實(shí)現(xiàn)create()和update()方法。
使用我們的序列化程序編寫常規(guī)的Django視圖
編輯snippets/views.py文件良漱,并添加以下內(nèi)容舞虱。
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<pk>[0-9]+)/$',views.snippet_detail),
]
安裝調(diào)試工具
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"
}