Restful API serialize相關

官網:https://www.django-rest-framework.org/tutorial/1-serialization/html

總結以下:python

1、序列化django

定義modeljson

class Snippet(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default='')

定義對應的Serializerapi

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()

 

序列化過程ui

#序列化
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"}'

                                                                                                                                                                                                                                 

2、反序列化spa

把byte轉化成原生string,再pase成rest

import io
#讀入json數據流, stream = io.BytesIO(content)

#轉換成python原生string
data = JSONParser().parse(stream)code

#原生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\fileorm

https://www.jianshu.com/p/b74a83e0f9fc

http://www.javashuo.com/article/p-byqtrdud-nq.html

 

3、簡潔(常規)的寫法 

一、model簡化

#相似於modelForm,自動引入field,還默認有  and  操做。
class SnippetSerializer(serializers.ModelSerializer): class Meta: model = Snippet fields = ['id', 'title', 'code', 'linenos', 'language', 'style']


create()update()
#相似於普通Form
class SnippetSerializer(serializers.Serializer): code = serializers.CharField(style={'base_template': 'textarea.html'})

 二、用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)
#
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)request.data 接收提交的json,轉換成原生string

 

rest api的方法

相關文章
相關標籤/搜索