前言:昨天學習了rest-framework序列化方面的知識,故寫了博客記錄一下。官網:http://www.django-rest-framework.org/tutorial/1-serialization/#working-with-serializers。html
先後端分離:前臺的開發和後臺的開發分離開。這個方案的實現就是要藉助API,API簡單說就是開發人員提供編程接口被其餘人調用,他們調用以後會返回數據供其使用。API的類型有多種,可是如今比較主流且實用的就是RESTful API。前端
Okay, we're ready to get coding. To get started, let's create a new project to work with.首先建立一個Django項目。python
cd ~ django-admin.py startproject tutorial cd tutorial
Once that's done we can create an app that we'll use to create a simple Web API.接着建立一個APPshell
python manage.py startapp snippets
We'll need to add our new snippets
app and the rest_framework
app to INSTALLED_APPS
. Let's edit the tutorial/settings.py
file:修改全局配置文件。數據庫
INSTALLED_APPS = ( ... 'rest_framework', 'snippets.apps.SnippetsConfig', )
Please note that if you're using Django <1.9, you need to replace snippets.apps.SnippetsConfig
with snippets
.django
若是你使用的Django <1.9,則須要更換snippets.apps.SnippetsConfig爲
snippets
。編程
For the purposes of this tutorial we're going to start by creating a simple Snippet
model that is used to store code snippets(片斷). Go ahead and edit the snippets/models.py
file.json
咱們將首先建立一個Snippet
用於存儲代碼片斷的簡單模型,編輯snippets/models.py
文件。後端
from django.db import models # Create your models here.
# pygments能夠實現代碼高亮 官網:http://pygments.org/
from pygments.lexers import get_all_lexers # 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',) # 根據建立時間來排序
初始化而且同步到數據庫:api
python manage.py makemigrations snippets
python manage.py migrate
The first thing we need to get started on our Web API is to provide a way of serializing(序列化) and deserializing(反序列化) the snippet instances into representations such as json
. We can do this by declaring(聲明) serializers that work very similar to Django's forms.
首先我要問你了,一般狀況下,前端從調用後臺API,API確定須要返回數據給前端,那返回的數據是什麼類型呢?
目前主流用的比較多的是JSON,可能有少部分還在用XML。
那咱們在學習django-rest-framework時,有沒有提供什麼方法可以將數據實例信息自動轉換爲JSON?並且也能夠將前端傳給後臺的JSON數據轉換爲python的數據類型(dict/list/set...)。固然有,序列化器(serializers)能夠實現。首先你得聲明(引入)序列化器,請看下面這個例子:
# 用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) # 利用字段標誌控制序列化器渲染到HTML頁面時的的顯示模板
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): """ The create() and update() methods define how fully fledged instances are created or modified when calling serializer.save() Create and return a new `Snippet` instance, given the validated data. 給定通過驗證的數據,建立並返回一個新的 Snippet 實例 """
return Snippet.objects.create(**validated_data) def update(self, instance, validated_data): """ Update and return an existing `Snippet` instance, given the 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
序列化器類的第一部分定義了序列化/反序列化的字段。該create()
和update()
方法分別定義實例如何建立和更新。
關於下面這行代碼:
code = serializers.CharField(style={'base_template': 'textarea.html'})
暫時須要知道的就是它的功能是控制序列化器渲染到HTML頁面時的的顯示模板,至於爲何要這樣作,是由於這對於控制如何顯示可瀏覽的API特別有用,這將在後面的文章中看到。
實際上也能夠經過使用ModelSerializer
來節省本身的時間,咱們稍後會看到,接下來看看序列化器的具體做用。
在咱們進一步瞭解以前,咱們將熟悉使用咱們新的Serializer類。咱們進入Django shell:
python manage.py shell
接下來的操做就和學習Django的ORM時那樣,建立並保存Snippet模型實例:
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'}
At this point we've translated the model instance into Python native datatypes.
從上面的代碼,能夠看到,咱們已經將model的實例信息轉換爲python原生的數據類型,即字典。
To finalize the serialization process we render the data into json
.
爲了完成序列化過程,咱們將數據轉換成json
。
content = JSONRenderer().render(serializer.data)
content
# '{"id": 2, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false, "language": "python", "style": "friendly"}'
這裏已經出現了json格式,也就是說這個json格式的數據就是要展現在某個URL上,大概能夠感受到,等下咱們在訪問某個URL時,會返回上面這堆數據供你使用,這其實就完成了一個序列化的過程,也能夠看出客戶端的功能雛形。
序列化是爲了返回json格式的數據給客戶端查看和使用數據,那麼當客戶端須要修改、增長或者刪除數據時,就要把過程反過來了,也就是反序列化,把客戶端提交的json格式的數據反序列化。
反序列化是相似的。首先咱們將一個流解析爲Python本機數據類型...
from django.utils.six import BytesIO stream = BytesIO(content) data = JSONParser().parse(stream)
...then we restore those native datatypes into a fully populated object instance.
先檢查數據是否有誤,再保存數據:
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>
這個時候查看數據庫又多了一條數據:
We can also serialize querysets instead of model instances. To do so we simply add a many=True
flag to the serializer arguments.
咱們也能夠序列化查詢集而不是模型實例。爲此,咱們只須要爲serializer參數添加一個標誌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')])]
在上面的SnippetSerializer類中,咱們繼承的是serializers.Serializer類,能夠看到SnippetSerializer類中有不少代碼實際上是和models.py中的Snippet模型相似同樣的,因此這裏咱們能夠改進一下。就像在Django中提供了Form類和ModelForm類同樣,django-rest-framework爲咱們提供了Serializer類和ModelSerializer類。利用它可讓咱們的代碼簡潔不少,修改serializers.py:
# Our SnippetSerializer class is replicating a lot of information that's also contained in the Snippet model. # It would be nice if we could keep our code a bit more concise.
class SnippetSerializer(serializers.ModelSerializer): class Meta: model = Snippet fields = ('id', 'title', 'code', 'linenos', 'language', 'style')
One nice property that serializers have is that you can inspect(檢查/查看) all the fields in a serializer instance, by printing its representation. Open the Django shell with python manage.py shell
, then try the following:
序列化器具備的一個不錯的屬性是能夠經過打印其表示來檢查序列化器實例中的全部字段。打開Django shell python manage.py shell
,而後嘗試如下操做:
from snippets.serializers import SnippetSerializer serializer = SnippetSerializer() 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=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')... # style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')...
記住,ModelSerializer類不會作任何特別神奇的事情,它們只是建立序列化器類的快捷方式:
接下來要作的就是使用咱們的新的Serializer類編寫一些API視圖。編輯snippets/views.py:
from django.shortcuts import render # Create your views here. 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 @csrf_exempt def snippet_list(request): """ because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as csrf_exempt 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)
上面的代碼都比較好理解,定義了不一樣http動做時後臺不一樣的操做,在這裏也體現了restful API的理念。
because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as csrf_exempt
.
由於咱們但願可以從不具備CSRF令牌的客戶端對此視圖進行POST,所以咱們須要給視圖加個一個裝飾器csrf_exempt
爲了讓視圖函數被調用,那固然須要設計一下url了,這裏的處理和平時Django開發時是同樣的。首先建立snippets/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), ]
We also need to wire up the root urlconf, in the tutorial/urls.py
file, to include our snippet app's URLs.
from django.conf.urls import url, include
urlpatterns = [
url(r'^', include('snippets.urls')),
]
完成了上面那些工做後,就能夠開始測試了,退出shell模式並啓動服務器,根據咱們剛纔設計的url發送請求,須要先安裝httpie模塊:
pip install httpie
而後在命令行窗口訪問,效果以下:
也能夠訪問指定id的數據:
固然了,也能夠直接在瀏覽器查看,直接輸入那個URL就能夠了: