程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Serialization and deserialization, Django rest framework

編輯:Python

Deserialization , Deserialization is receiving from the front end json data , The process of converting to a data object , update operation 、 The save operation has a deserialization operation , Receiving front end -> Validation data -> Save or update to a new data object

Serialization converts the obtained data object into json data .

If you use the writing method of the previous article , Both deserialization and serialization should write their own code , In order to improve efficiency , Use Django Rest Framework, The deserialization and serialization code are encapsulated , Define a serializer Serializer, Can help automate deserialization and serialization

Django REST framework With the help of Django Framework to encapsulate the serializer

Install first DjangoRESTframework Module , You can use commands

1、pip install djangorestframework , have access to pycharm Of Python Interpreter Installation

2、 When you use it , Think of it as a new application , Note that this is not a new project , Can be directly in setting.py Register in

 'rest_framework',

3、 Import directly when using

from rest_framework.generics import ListAPIView, CreateAPIView, UpdateAPIView, RetrieveAPIView, DestroyAPIView

Directly inherit this class when using

for example

class BookCView(CreateAPIView)

Some in the CreateAPIView Source code of this class , It's found that it already has post request ,

class CreateAPIView(mixins.CreateModelMixin,
GenericAPIView):
"""
Concrete view for creating a model instance.
"""
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)

Continue to click in to see create Method

class CreateModelMixin:
"""
Create a model instance.
"""
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
def perform_create(self, serializer):
serializer.save()
def get_success_headers(self, data):
try:
return {'Location': str(data[api_settings.URL_FIELD_NAME])}
except (TypeError, KeyError):
return {}

From the source code, the first step is to obtain data

Then check the data

Save the data

Serialization returns data

DjangoRESTframework The serialization has been encapsulated for us 、 Deserialization , We can inherit these classes when we use them .

When you use it , Think of it as an application , Come first setting.py Register in rest_framework, Then use it from rest_framework.generics The introduction of package , Then inherit these classes .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved