Django Rest Framework学习进程(一) 序列化
首先是巴拉巴拉的开场白:博主是名在校的大专生,今年大二了,主学Python,现在想通过写博客的形式来记录我学习的过程,从而来督促我自己,本学习过程是通过阅读官方文档来实现的,官网文档的网址为:https://www.django-rest-framework.org
1.准备工作
首先,需要安装依赖包有:django、djangorestframework、pygments,这里通过pip命令直接安装,至于环境的配置问题,这里就不再进行赘述了,安装命令如下:
pip install django //本文基于django1.11版本来做
pip install djangorestframework
pip install pygments //实现代码的高亮
2.新建一个名字tutorial的项目
django-admin startproject tutorial
3.创建一个APP,名字叫snippets
//执行startapp命令来创建应用
python manage.py startapp snippets
//编辑tutorial/settings.py文件,将snippets和rest_framework加入到INSTALLED_APPS当中 INSTALLED_APPS = { ... 'snippets', 'rest_framework' }
4.创建一个snippets model
//在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',)
5.执行数据库迁移命令
python manage.py makemigrations snippets
python manage.py migrate
6.创建一个序列化类(SnippetSerializer)
#这个类的功能和Django中的forms有点类似 //在snippets下,新建一个serializers.py文件 //在snippets/serializers.py中,写入以下代码: from rest_framework import serializers from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES class SnippetSerializer(serializers.Serializer): """ 序列化器类的第一部分定义了序列化/反序列化的字段 create()和update()方法定义了在调用serializer.save()时如何创建和修改完整的实例。 """ 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
7.启动Django shell
//启动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 = Snippet(code='foo = "bar"\n') snippet.save() snippet = Snippet(code='print("hello, world")\n') snippet.save()
8.序列化与反序列化
#这里的snippet为上面实例出来的snippet对象 serializer = SnippetSerializer(snippet) serializer.data##执行结果:{'id': 2, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}
#将实例snippet转换为Python原生数据类型,为了完成这个序列化的过程,需将返回的serializer.data转换为JSON格式
content = JSONRenderer().render(serializer.data)
content##执行结果: b'{"id": 2, "title": "", "code": "print(\\"hello, world\\")\\n", "linenos": false, "language": "python", "style": "friendly"}'
#反序列化(还原序列化)的过程是类似的
#首先引入io模块,因为content是bytes类型的数据,所以这里调用BytesIO()这个方法,将这个流(stream)转换为Python原生数据类型
import io
stream = io.BytesIO(content)
data = JSONParser().parse(stream)
data
9.将Python原生数据类型转为实例对象
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>
10.序列化查询结果集
#上面在序列化的过程中,传的是Snippet对象,其实还可以传querysets对象 #只需要加入"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')])]
11.使用ModelSerializer类
#在snippets/serializers.py中,将SnippetSerializer类替换为以下内容 class SnippetSerializer(serializers.ModelSerializer): class Meta: model = Snippet fields = ('id', 'title', 'code', 'linenos', 'language', 'style') #运行python manage.py shell,写下以下代码: #通过打印实例的属性(representation)来查看所有字段 from snippets.serializers import SnippetSerializer serializer = SnippetSerializer() print(repr(serializer))
需要注意的是,ModelSerializer类没有做什么特别的事情,它只是一个创建序列化类的捷径:1.实现一组自动确定的字段 2.默认简单地实现create()和update()这两个方法
12.使用Serializer来编写Django的视图
#首先导入如下包 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代表这个视图不需要csrf令牌也能访问 #创建一个根视图函数,用来列出所有现有的snippet或创建一个新的snippet def snippet_list(request): """ 列出所有的code snippets,或创建一个新的snippet """ if request.method == "GET": snipppets = Snippet.objects.all() serializer = SnippetSerializer(snipppets,many=True) #将数据类型转为正常的实例的对象,通过data属性输出出来 return JsonResponse(serializer.data,safe=False) elif request.method == "POST": #对传过来的request做处理(假设这里传过来的是json格式的请求) 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): """ 获取,更新或删除一个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(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)
13.编写url路径
#首先,先在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), ] #接着,在tutorial/urls.py中,写入以下代码: from django.conf.urls import url,include urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^',include('snippets.urls')) ]
14.测试API
#首先,安装一个依赖包,名字叫httpie,httpie是用Python编写的用户友好的http客户端 pip install httpie #接着,使用python manage.py runserver 命令来启动Django #在网址中输入:http://127.0.0.1:8000/snippets/,可获取所有数据 #输入http://127.0.0.1:8000/snippets/2/,可获取指定的数据 #这样,最开始的第一步就完成啦,完结撒花先嘿嘿嘿~