Restful API serialize相关
官网:https://www.django-rest-framework.org/tutorial/1-serialization/
总结如下:
一、序列化
定义model
class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='')
定义对应的Serializer
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'})
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) #把序列化对象换成 python 原生类型string
serializer.data # {'id': 2, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}
#把原生类型string,转换成json,可以输出到页面
content = JSONRenderer().render(serializer.data)
content
# b'{"id": 2, "title": "", "code": "print(\\"hello, world\\")\\n", "linenos": false, "language": "python", "style": "friendly"}'
二、反序列化
把byte转化成原生string,再pase成
import io
#读入json数据流,
stream = io.BytesIO(content)
#转换成python原生string
data = JSONParser().parse(stream)
#原生string赋值给serialzer对象
serializer = SnippetSerializer(data=data) serializer.is_valid() # True serializer.validated_data # OrderedDict([('title', ''), ('code', 'print("hello, world")\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])
#保存成django的model对象。
serializer.save() # <Snippet: Snippet object>
文件或流读入读出的参考:BytesIO\file
https://www.jianshu.com/p/b74a83e0f9fc
https://www.cnblogs.com/yqpy/p/8556090.html
三、简洁(常规)的写法
1、model简化
#类似于modelForm,自动引入field,还默认有create()
andupdate()
操作。
class SnippetSerializer(serializers.ModelSerializer): class Meta: model = Snippet fields = ['id', 'title', 'code', 'linenos', 'language', 'style']
#类似于普通Form
class SnippetSerializer(serializers.Serializer): code = serializers.CharField(style={'base_template': 'textarea.html'})
2、用drf的request,response简化
django :request.POST # Only handles form data. Only works for 'POST' method.
drf :request.data # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods.
return Response(data)
@api_view(['GET', 'POST'])
def singer_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 Response(serializer.data)
#用Response输出到终端,代替《JSONRenderer().render(serializer.data) 》,简洁省事。
elif request.method == 'POST': serializer = SnippetSerializer(data=request.data)
#request.data 接收提交的
json,转换成原生string
if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
rest api的方法