将一种对象的状态信息装换成可以存储或者可以传输形式的过程。比如将模型类转换成JSON数据,整个过程将序列化(序列化和反序列化执行的过程相似的,也就是可以封装代码)
python manage.py startapp snippets
# 配置
INSTALLED_APPS = (
...
'rest_framework',
'snippets.apps.SnippetsConfig',
)
写一个代码片段model 带代码高亮
# snippets/models.py
# pygment 用于代码高亮
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
创建几个代码片段
# 进入shell
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='foo = "bar"\n')
snippet.save()
snippet = Snippet(code='print("hello, world")\n')
snippet.save()
# 来看看序列化其中一个实例
serializer = SnippetSerializer(snippet)
serializer.data
# {'id': 2, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}
# 已将模型实例转换为Python本机数据类型
content = JSONRenderer().render(serializer.data)
content
# b'{"id": 2, "title": "", "code": "print(\\"hello, world\\")\\n", "linenos": false, "language": "python", "style": "friendly"}'
# 反序列化是类似的 首先,我们将流解析为Python本机数据类型
import io
stream = io.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()
#
# 查询多少对象时,需要设置many=True
serializer = SnippetSerializer(Snippet.objects.all(), many=True)
serializer.data
# [OrderedDict([('id', 1), ('title', ''), ('code', 'foo = "bar"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 2), ('title', ''), ('code', 'print("hello, world")\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 3), ('title', ''), ('code', 'print("hello, world")'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])]
这是我们建议采用的模式,与Django提供Form
类和ModelForm
类的方式相同,REST框架包括Serializer
类和ModelSerializer
类。现在我们用ModelSerializers重构snippets/serializers.py
。。。
class SnippetSerializer(serializers.ModelSerializer):
class Meta:
model = Snippet
fields = ('id', 'title', 'code', 'linenos', 'language', 'style')
。。。
打开shell 我们验证一下:
from snippets.serializers import SnippetSerializer
serializer = SnippetSerializer()
print(repr(serializer))
## repr() 函数将对象转化为供解释器读取的形式
# 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 在这里主要做两件事:
create()
和update()
方法编辑snippets/views.py文件,并添加以下内容
# snippets/views.py
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
@csrf_exempt # 跳过csrf认证
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)
添加snippets/urls.py
# snippets/urls.py
from django.urls import path
from snippets import views
# root-snippets/
urlpatterns = [
path('snippets/', views.snippet_list),
path('snippets//', views.snippet_detail),
]
修改tutorial/urls.py
urlpatterns = [
path('', include(router.urls)),
# 包含默认登录和注销,身份验证
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
path('root-snippets/', include('snippets.urls')),
]
启动项目,这里可以用Postman测试也可以直接通过浏览器访问。
访问:
http://127.0.0.1:8000/root-snippets/snippets/
http://127.0.0.1:8000/root-snippets/snippets/2/
访问结果如下:
个人感受:
这部分相对与采用rest 框架的View来说, 直接使用django.http.JsonResponse+django.core.serializers(以前我就是这样干的)能实现更加灵活的自定义接口API。
现在对rest-framework 和直接JsonResponse自己封装的json格式response的区别不太清楚。
前者可能对比较规范的model开发接口会方便些,复杂些的估计够呛(目前学的还不深入),但采用的设计思想都是一样的,都是有浏览器发ajax请求,服务器不在返回渲染好的html以及模型数据了,而是json数据,将渲染的任务给了浏览器,这也是前后端分离的原理。