当前位置:网站首页>DRF defines views and routes
DRF defines views and routes
2022-07-07 09:11:00 【FOR. GET】
One 、DRF Medium Request And Response
Two 、APIView
APIViewyesDRFBase class for all views provided , Inherited fromDjangoOfView. The difference is :
- The incoming view method object is different :
DRFyesRequest,DJangoyesHTTPRequest DRFThe view method can returnResponseobject , The view sets... For the response data (render) Conform to the format of the front endAPIExceptionExceptions will be caught , And process it into appropriate response information- It's going on
dispatch()Before distribution , The request will be Identity Authentication 、 Permission check 、 flow control etc. APIViewIt is still implemented in the conventional class view definitionget、postWait for the request method
from rest_framework import serializers
from book.models import Book,Publish
# class Publish(serializers.ModelSerializer):
# class Meta:
# model = Publish
# fields = ['publish',]
class BookModelSerializer(serializers.ModelSerializer):
# publish = Publish()
class Meta:
model = Book
fields = '__all__'
# views.py
''' List view : GET /books/ Provide all records POST /books/ Add a record Detail view : GET /books/<str:pk>/ Provide a record PUT /books/<str:pk>/ Modify a record DELETE /books/<str:pk>/ Delete a record APIView + ModelSerializer '''
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from book.models import Book
from book.serializers import BookModelSerializer
class BookListAPIView(APIView):
""" List view """
def get(self,request):
''' Query all '''
# Check all the books
books = Book.objects.all()
# Serialized data
serializer = BookModelSerializer(books,many=True)
print(serializer.data)
res = Response(serializer.data)
# 1).data Pass to response After serialization of object , But not yet render Data processed
print(res.data)
# 2).status_code The number of the status code
print(res.status_code)
# 3).content after render Processed response data
# print(res.content)
# Status code default 200
return Response(serializer.data)
def post(self,request):
''' Add a new one '''
# Get the request body data transmitted from the front end
data = request.data
# Create a serializer to deserialize
serializer = BookModelSerializer(data=data)
# Calling the serializer is_valid() Method for verification
serializer.is_valid(raise_exception=True)
# Calling the serializer save Method to execute create Method
serializer.save()
# Respond to
return Response(data=serializer.data,status=status.HTTP_201_CREATED)
class BookDetailAPIView(APIView):
""" Detail view """
def get(self,request,pk):
# Query as pk Model object
book = Book.objects.filter(pk=pk).first()
if not book:
return Response(status=status.HTTP_404_NOT_FOUND)
else:
# Use serializer classes for serialization
serializer = BookModelSerializer(instance=book)
return Response(serializer.data)
def put(self,request,pk):
# It is amended as follows pk The model object of
book = Book.objects.filter(pk=pk).first()
if not book:
return Response(status=status.HTTP_404_NOT_FOUND)
else:
data = request.data
serializer = BookModelSerializer(instance=book,data=data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data)
def delete(self,request,pk):
# It is amended as follows pk The model object of
book = Book.objects.filter(pk=pk).first()
if not book:
return Response(status=status.HTTP_404_NOT_FOUND)
else:
book.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
# urls.py
from django.contrib import admin
from django.urls import path
from book.views import BookListAPIView,BookDetailAPIView
from rest_framework.routers import DefaultRouter
urlpatterns = [
path('admin/', admin.site.urls),
path('books/',BookListAPIView.as_view()),
path('books/<str:pk>/',BookDetailAPIView.as_view())
]lo9
# # Appoint DRF-ModelView route
# router = DefaultRouter()
# router.register(r'api/books',BookView)
# urlpatterns += router.urls
When adding or modifying , If there are foreign keys , You need to put the associated part of the foreign key into it to add .
3、 ... and 、GenericAPIView
Inherited from
APIView, The method of operating serializer and database query is mainly added , The function is toMixinExtension class execution provides support , It is often used with one or moreMixinThe extension class . Except for inheritanceAPIViewIdentity Authentication 、 Permission check 、 flow control Besides these three functions , And new Pagination and Filter .
3.1 GenericAPIView Use alone
- List view :
self.get_queryset() - Detail view :
self.get_object(), There's morepk, Or other parameters
""" Later, when facing other serialization classes and data sources , Just replace step1 and step2 that will do """
class BookListGenericView(GenericAPIView):
""" List view """
# step1 Specifies the serializer class
serializer_class = BookModelSerializer
# step2 Specify query set , That is to clarify the data source
queryset = Book.objects.all()
# step3 Define the request method function
def get(self,request):
qs = self.get_queryset()
serializer = self.get_serializer(qs,many=True)
return Response(serializer.data)
# The rest is the same as above post
''' For details view , You only need to specify the query later pk that will do lookup_field = 'pk' If you need to change the query pk Modifiable lookup_field For the field name you need to query '''
class BookDetailGenericView(GenericAPIView):
""" List view """
# step1 Specifies the serializer class
serializer_class = BookModelSerializer
# step2 Specify query set , That is to clarify the data source
queryset = Book.objects.all()
# step3 Define the request method function
def get(self,request,pk):
book = self.get_object()
serializer = self.get_serializer(book)
return Response(serializer.data)
# The rest is the same as above put delete
urlpatterns = [
path('admin/', admin.site.urls),
# path('books/',BookListAPIView.as_view()),
# path('books/<str:pk>/',BookDetailAPIView.as_view()),
path('books/',BookListGenericView.as_view()),
path('books/<str:pk>/',BookDetailGenericView.as_view())
]
3.2 GenericAPIView & Mixin Implementation interface
Provides several back-end views ( Delete, modify and check the data resources ) The implementation of the process , If the views you need to write fall into these five categories , Then the view can reuse the code by inheriting the corresponding extension class , Reduce the amount of code you write . These five extension classes need to be matched
GenericAPIViewParent class , Because the implementation of the five extension classes needs to callGenericAPIViewProvides the serializer and the database query method .
1)ListModelMixin
List view extension class , Provide
list(request, *args, **kwargs)Method to quickly implement the list view , return 200 Status code . The Mixin Of list Method will filter and paginate the data .
2)CreateModelMixin
Create a view extension class , Provide
create(request, *args, **kwargs)Method to quickly create a view of resources , Successfully returns201Status code . If the serializer fails to verify the data sent by the front end , return400error .
3)RetrieveModelMixin
Detail view extension class , Provide
retrieve(request, *args, **kwargs)Method , It can quickly return an existing data object . If there is , return200, Otherwise return to404.
4)UpdateModelMixin
Update view extension class , Provide
update(request, *args, **kwargs)Method , Can quickly update an existing data object . It also providespartial_update(request, *args, **kwargs)Method , Local update can be achieved . Successfully returns200, When the serializer fails to verify data , return400error .
5)DestroyModelMixin
Delete view extension class , Provide
destroy(request, *args, **kwargs)Method , It can quickly delete an existing data object . Successfully returns204, There is no return404.
class BookListMixinGenericView(ListModelMixin, CreateModelMixin, GenericAPIView):
# Specifies the serializer class
serializer_class = BookModelSerializer
# Specify data sources
queryset = Book.objects.all()
def get(self, request):
return self.list(request)
def post(self, request):
return self.create(request)
class BookDetailMixinGenericView(RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin, GenericAPIView):
# Specifies the serializer class
serializer_class = BookModelSerializer
# Specify data sources
queryset = Book.objects.all()
def get(self, request, pk):
return self.retrieve(request, pk)
def put(self, request, pk):
return self.update(request, pk)
def delete(self, request, pk):
return self.destroy(request, pk)
3.3 ListAPIView & CreateAPIView & ListCreateAPIView …
1)CreateAPIView
Provide
postMethodInherited from :
GenericAPIView、CreateModelMixin
2)ListAPIView
Provide
getMethodInherited from :
GenericAPIView、ListModelMixin
3)RetrieveAPIView
Provide
getMethodInherited from :
GenericAPIView、RetrieveModelMixin
4)DestoryAPIView
Provide
deleteMethodInherited from :
GenericAPIView、DestoryModelMixin
5)UpdateAPIView
Provide put and patch Method
Inherited from :
GenericAPIView、UpdateModelMixin
6)RetrieveUpdateAPIView
Provide
get、put、patchMethodInherited from :
GenericAPIView、RetrieveModelMixin、UpdateModelMixin
7)RetrieveUpdateDestoryAPIView
Provide
get、put、patch、deleteMethodInherited from :
GenericAPIView、RetrieveModelMixin、UpdateModelMixin、DestoryModelMixin
class BookListMixinGenericView(ListModelMixin, CreateModelMixin, GenericAPIView):
# Specifies the serializer class
serializer_class = BookModelSerializer
# Specify data sources
queryset = Book.objects.all()
def get(self, request):
return self.list(request)
def post(self, request):
return self.create(request)
class BookListMixinGenericView(ListAPIView,CreateAPIView):
# Specifies the serializer class
serializer_class = BookModelSerializer
# Specify data sources
queryset = Book.objects.all()
class BookListMixinGenericView(ListCreateAPIView):
# Specifies the serializer class
serializer_class = BookModelSerializer
# Specify data sources
queryset = Book.objects.all()
Four 、 View set
View set : Previously, it was written by separating the detail view and the list view , Because there are two
getrequest ( Query all and individual ), The purpose of view set is to unify these interfaces , Write these two views into the same view class , And be able to customize other methods
4.1 ViewSet
Using view sets
ViewSet, You can put a series of logically related actions into a class :
- list() Provide a set of data
- retrieve() Provide single data
- create() Create data
- update() Save the data
- destory() Delete data
ViewSetThe view set class is no longer implementedget()、post()Other methods , It's about actingactionSuch aslist()、create()etc. . View sets are only usedas_view()Method time , Will beactionThe action corresponds to the specific request mode .
class BookViewSet(ViewSet):
""" View set : Previously, it was written by separating the detail view and the list view , Because there are two get request ( Query all and individual ), The purpose of view set is to unify these interfaces , Write these two views into the same view class , And be able to customize other methods """
def list(self,request):
# Query all
books = Book.objects.all()
# Query set to add many=True
serializer = BookModelSerializer(books,many=True)
return Response(serializer.data)
def create(self,request):
serializer = BookModelSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data)
def retrieve(self,request,pk):
# Inquire about pk by pk The object of
book = Book.objects.filter(pk=pk).first()
if not book:
return Response(status=status.HTTP_404_NOT_FOUND)
else:
serializer = BookModelSerializer(book)
return Response(serializer.data)
def update(self,request,pk):
# Inquire about pk by pk The object of
book = Book.objects.filter(pk=pk).first()
if not book:
return Response(status=status.HTTP_404_NOT_FOUND)
else:
# data From the front json data
serializer = BookModelSerializer(book, data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
def destroy(self,request,pk):
book = Book.objects.filter(pk=pk).first()
if not book:
return Response(status=status.HTTP_404_NOT_FOUND)
else:
book.delete()
return Response(status.HTTP_204_NO_CONTENT)
urlpatterns = [
path('admin/', admin.site.urls),
# path('books/',BookListAPIView.as_view()),
# path('books/<str:pk>/',BookDetailAPIView.as_view()),
# path('books/',BookListGenericView.as_view()),
# path('books/<str:pk>/',BookDetailGenericView.as_view()),
path('books/',BookViewSet.as_view({
'get':'list','post':'create'})),
path('books/<str:pk>/',BookViewSet.as_view({
'get':'retrieve','put':'update','delete':'destory'}))
]
4.2 GenericViewSet
Use
ViewSetIt's usually not convenient , becauselist、retrieve、create、update、destoryWe need to write our own methods , And these methods are different from the ones mentioned aboveMixinThe method provided by the extension class has the same name , So we can inheritMixinExtend classes to reuse these methods without having to write your own . howeverMixinExtension classes depend onGenericAPIView, So we need to inheritGenericAPIView.
GenericViewSetIt helps us to finish this kind of inheritance work , Inherited fromGenericAPIViewAndViewSetMixin, In the implementation of the callas_view()When you enter the dictionary ( Such as{'get':'list'}) At the same time that the mapping process works , It also providesGenericAPIViewBasic methods provided , It can be directly matched withMixinExtension classes use .
ModelViewSet
Inherited from
GenericViewSet, It also includesListModelMixin、RetrieveModelMixin、CreateModelMixin、UpdateModelMixin、DestoryModelMixin
ReadOnlyModelViewSet
Inherited from
GenericViewSet, It also includesListModelMixin、RetrieveModelMixin
class BookViewSet(ListModelMixin,RetrieveModelMixin,GenericViewSet):
# class BookViewSet(ModelViewSet):
""" View set : Previously, it was written by separating the detail view and the list view , Because there are two get request ( Query all and individual ), The purpose of view set is to unify these interfaces , Write these two views into the same view class , And be able to customize other methods """
queryset = Book.objects.all()
serializer_class = BookModelSerializer
class BookViewSet(ReadOnlyModelViewSet):
# class BookViewSet(ModelViewSet):
""" ReadOnlyModelViewSet: books/ & books/1/ get request ModelViewSet: books/ & books/1/ get request put delete """
queryset = Book.objects.all()
serializer_class = BookModelSerializer
""" Additional definitions none pk """
# Behavior defined outside the usual addition, deletion, modification, and query , It should be routed separately
# If this behavior does not need to add pk, Then it is the list view ,
# But the list view only has list create
# URL:path(r'books/latest/',BookViewSet.as_view({'get':'latest'}))
"""action Detailed explanation of decorator parameters methods: This operation responds to HTTP Method name list . Default only GET. detail: Necessary parameters . Determine whether this operation applies to the instance / Detailed information request or collection / List request .detail=False Not a detail view ;detail=TRUE Is the detail view url_path: Define URL paragraph . The default is the name of the decorated method . url_name: Define the interior for this action (' reverse ') URL name . The default is method name , Replace dashes with underscores . """
@action(methods="get",detail=False)
def latest(self,request):
pass
""" Additional definitions are pk """
# Yes pk Is the detail view
# The detail view has :get put delete
# URL:path(r'books/<int:pk>/latest/',BookViewSet.as_view({'get':'read'}))
@action(methods='get',detail=True)
def title(self, request,pk):
book = self.get_object()
book.title = request.data['title']
book.save()
# return Response(self.get_serializer(book).data)
pass
4.3 Route definition
General definition
""" Additional definitions none pk """
# Behavior defined outside the usual addition, deletion, modification, and query , It should be routed separately
# If this behavior does not need to add pk, Then it is the list view ,
# But the list view only has list create
# URL:path(r'books/latest/',BookViewSet.as_view({'get':'latest'}))
""" Additional definitions are pk """
# Yes pk Is the detail view
# The detail view has :get put delete
# URL:path(r'books/<int:pk>/latest/',BookViewSet.as_view({'get':'read'}))
DefaultRouter & SimpleRouter Definition
# # Appoint DRF-ModelView route
# This method is only suitable for use in view sets , And can only generate standard add, delete, modify and check these five basic routes
# If you want to customize the behavior, you can also generate routes , It needs to be used in custom behavior action Behavior , And specify the corresponding request method
"""action Detailed explanation of decorator parameters methods: This operation responds to HTTP Method name list . Default only GET. detail: Necessary parameters . Determine whether this operation applies to the instance / Detailed information request or collection / List request .detail=False Not a detail view ;detail=TRUE Is the detail view url_path: Define URL paragraph . The default is the name of the decorated method . url_name: Define the interior for this action (' reverse ') URL name . The default is method name , Replace dashes with underscores . """
# DefaultRouter,SimpleRouter The only difference :DefaultRouter A root route will be generated by default ,SimpleRouter Can't
# router = DefaultRouter()
# router.register(r'api/books',BookViewSet)
# urlpatterns += router.urls
边栏推荐
- PMP Exam details after the release of the new exam outline
- [istio introduction, architecture, components]
- [chaosblade: node disk filling, killing the specified process on the node, suspending the specified process on the node]
- C language pointer (exercises)
- Common operating commands of Linux
- Skill review of test engineer before interview
- Confitest of fixture py
- Original collection of hardware bear (updated on May 2022)
- Druid monitoring - Introduction to JMX usage and principle
- OpenGL帧缓冲
猜你喜欢

PMP examination experience sharing

Serial port experiment - simple data sending and receiving

H3C vxlan configuration

NVIC interrupt priority management

【Istio Network CRD VirtualService、Envoyfilter】

Platformization, a fulcrum of strong chain complementing chain

How to pass the PMP Exam in a short time?

C language pointer (Part 2)

MySQL common statements
![Pytest+request+allure+excel interface automatic construction from 0 to 1 [familiar with framework structure]](/img/33/9fde4bce4866b988dd2393a665a48c.jpg)
Pytest+request+allure+excel interface automatic construction from 0 to 1 [familiar with framework structure]
随机推荐
LeetCode 736. LISP syntax parsing
Druid monitoring - Introduction to JMX usage and principle
数据在内存中的存储
ChaosBlade:混沌工程简介(一)
外部中断实现按键实验
Systick滴答定时器
模拟卷Leetcode【普通】1567. 乘积为正数的最长子数组长度
Digital triangle model acwing 275 Pass a note
MySql数据库-事务-学习笔记
寄存器地址名映射
Calculation s=1+12+123+1234+12345 C language
Several common database connection methods
Alibaba P8 teaches you how to realize multithreading in automated testing? Hurry up and stop
E-commerce campaign Guide
Unity shader beginner's Essentials (I) -- basic lighting notes
Interview question: general layout and wiring principles of high-speed PCB
Simulation volume leetcode [general] 1567 Length of the longest subarray whose product is a positive number
Simulation volume leetcode [general] 1609 Parity tree
LED模拟与数字调光
What is the value of getting a PMP certificate?