当前位置:网站首页>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
APIView
yesDRF
Base class for all views provided , Inherited fromDjango
OfView
. The difference is :
- The incoming view method object is different :
DRF
yesRequest
,DJango
yesHTTPRequest
DRF
The view method can returnResponse
object , The view sets... For the response data (render
) Conform to the format of the front endAPIException
Exceptions 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. APIView
It is still implemented in the conventional class view definitionget
、post
Wait 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 toMixin
Extension class execution provides support , It is often used with one or moreMixin
The extension class . Except for inheritanceAPIView
Identity 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
GenericAPIView
Parent class , Because the implementation of the five extension classes needs to callGenericAPIView
Provides 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 returns201
Status code . If the serializer fails to verify the data sent by the front end , return400
error .
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 , return400
error .
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
post
MethodInherited from :
GenericAPIView
、CreateModelMixin
2)ListAPIView
Provide
get
MethodInherited from :
GenericAPIView
、ListModelMixin
3)RetrieveAPIView
Provide
get
MethodInherited from :
GenericAPIView
、RetrieveModelMixin
4)DestoryAPIView
Provide
delete
MethodInherited from :
GenericAPIView
、DestoryModelMixin
5)UpdateAPIView
Provide put and patch Method
Inherited from :
GenericAPIView
、UpdateModelMixin
6)RetrieveUpdateAPIView
Provide
get
、put
、patch
MethodInherited from :
GenericAPIView
、RetrieveModelMixin
、UpdateModelMixin
7)RetrieveUpdateDestoryAPIView
Provide
get
、put
、patch
、delete
MethodInherited 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
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
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
ViewSet
The view set class is no longer implementedget()
、post()
Other methods , It's about actingaction
Such aslist()
、create()
etc. . View sets are only usedas_view()
Method time , Will beaction
The 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
ViewSet
It's usually not convenient , becauselist
、retrieve
、create
、update
、destory
We need to write our own methods , And these methods are different from the ones mentioned aboveMixin
The method provided by the extension class has the same name , So we can inheritMixin
Extend classes to reuse these methods without having to write your own . howeverMixin
Extension classes depend onGenericAPIView
, So we need to inheritGenericAPIView
.
GenericViewSet
It helps us to finish this kind of inheritance work , Inherited fromGenericAPIView
AndViewSetMixin
, 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 providesGenericAPIView
Basic methods provided , It can be directly matched withMixin
Extension 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
边栏推荐
- Upgrade Alibaba cloud RDS (relational database service) instance to com mysql. jdbc. exceptions. Troubleshooting of jdbc4.communicationsexception
- How to use Arthas to view class variable values
- Platformization, a fulcrum of strong chain complementing chain
- Locust performance test 2 (interface request)
- Unity Shader入门精要初级篇(一)-- 基础光照笔记
- Synchronized underlying principle, volatile keyword analysis
- Recommended by Alibaba P8, the test coverage tool - Jacobo is very practical
- C language pointer (Part 1)
- C语言指针(上篇)
- JVM garbage collection detailed learning notes (II)
猜你喜欢
LeetCode 736. LISP syntax parsing
NVIC中断优先级管理
What are the conditions for applying for NPDP?
2021 year end summary
Simple use of Xray
Synchronized underlying principle, volatile keyword analysis
External interrupt to realize key experiment
MySQL主从延迟的解决方案
MySQL master-slave delay solution
为不同类型设备构建应用的三大更新 | 2022 I/O 重点回顾
随机推荐
Chaosblade: introduction to chaos Engineering (I)
The longest ascending subsequence model acwing 1017 Strange thief Kidd's glider
PPT模板、素材下载网站(纯干货,建议收藏)
Count the number of words in the string c language
JVM 垃圾回收 详细学习笔记(二)
Port multiplexing and re imaging
Confitest of fixture py
Skills that testers must know: Selenium's three waiting ways are interpreted clearly
ESP32-ULP协处理器低功耗模式RTC GPIO中断唤醒
寄存器地址名映射
Count the number of words C language
How does the project manager write the weekly summary and weekly plan?
Simple use of Xray
Ppt template and material download website (pure dry goods, recommended Collection)
Simulation volume leetcode [general] 1557 The minimum number of points that can reach all points
NVIC interrupt priority management
硬核分享:硬件工程师常用工具包
端口复用和重映像
UnityShader入门精要个人总结--基础篇(一)
C语言指针(上篇)