当前位置:网站首页>DRF learning notes (IV): DRF view
DRF learning notes (IV): DRF view
2022-07-27 16:18:00 【fresh_ nam】
List of articles
One 、Request And Response
1.Request
REST framework Of the incoming view request Object is no longer Django default HttpRequest object , It is REST framework Provides an extension of HttpRequest Class Request Class object .
REST framework Provides Parser Parser , After receiving the request, it will automatically according to Content-Type Specified request data type ( Such as JSON、 Forms, etc ) The requested data is processed parse analysis , Resolve to class dictionary object and save to Request In the object .
Request The data of the object is automatically parsed according to the format of the data sent by the front end .
No matter what format of data sent by the front end , We can all read data in a unified way
Common properties
.data
request.data Return the request body data after parsing . Be similar to Django Medium standard request.POST and request.FILES attribute , But it provides the following features :
- Contains the parsed file and non file data
- Contains the right POST、PUT、PATCH Data parsed by request mode
- Take advantage of REST framework Of parsers Parser , Not only does it support form type data , Also support JSON data
.query_params
request.query_params And Django The standard request.GET identical , It's just a change of name .
2.Response
rest_framework.response.Response
REST framework Provides a response class Response, When using this class to construct response objects , The specific data content of the response will be transformed (render Rendering ) Into a type that meets the needs of the front end .
REST framework Provides Renderer Renderers , It is used according to Accept( Receive data type declaration ) To automatically convert the response data to the corresponding format . If not in the front end request Accept Statement , The response data is processed by default , We can modify the default response format through configuration .
Parameters
Response(data, status=None, template_name=None, headers=None, content_type=None)
data Data don't have to be render Data after processing , Just transfer python The built-in type data of ,REST framework Will use renderer The renderer handles data.
data It can't be data with complex structure , Such as Django Model class object , For such data, we can use Serializer After serializer serialization processing ( Into the Python Dictionary type ) And pass it on to data Parameters .
explain :
- data: Serialized data prepared for the response ;
- status: Status code , Default 200;
- template_name: Template name , If you use HTMLRenderer It needs to be specified when necessary ;
- headers: A dictionary for storing response header information ;
- content_type: Response data Content-Type, Usually this parameter does not need to be passed ,REST framework This parameter will be set according to the type data required by the front end .
Common properties
- .data: Pass to response After serialization of object , But not yet render Data processed
- .status_code: The number of the status code
- .content: after render Processed response data
Two 、 View description
1. Two base classes
1)APIView
rest_framework.views.APIView
APIView yes REST framework Base class for all views provided , Inherited from Django Of View Parent class .
APIView And View The difference is that :
- What's passed into the view method is REST framework Of Request object , instead of Django Of HttpRequeset object ;
- The view method can return REST framework Of Response object , The view sets... For the response data (render) Format according to front end requirements ;
- whatever APIException Exceptions are caught in , And process it into appropriate response information ;
- It's going on dispatch() Before distribution , The request will be authenticated 、 Permission check 、 flow control .
Support defined properties :
- authentication_classes List or Yuanzu , Identity authentication
- permissoin_classes List or Yuanzu , Permission check class
- throttle_classes List or Yuanzu , Flow control class
stay APIView The general class view definition method is still used in get() 、post() Or other ways of requesting .
Use :
demo/views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from demo.models import StudentInfo
from demo.serializers import StudentInfoSerializer
# Create your views here.
class StudentListView(APIView):
def get(self, request):
students = StudentInfo.objects.all()
serializer = StudentInfoSerializer(students, many=True) # When serializing multiple objects many by True
return Response(serializer.data)
add to url:
demo/urls.py
from django.urls import path, include
from demo import views
urlpatterns = [
path('students/', views.StudentListView.as_view())
]
The root path of the project urls.py add to :
urlpatterns = [
......
path('demo/', include('demo.urls')),
]
result :
2)GenericAPIView
rest_framework.generics.GenericAPIView
Inherited from APIVIew, The method of operating serializer and database query is mainly added , The function is to Mixin The execution of extension classes provides method support . Usually in use , Can be paired with one or more Mixin The extension class .
Provides information about the properties and methods used by the serializer
attribute :
serializer_class Indicates the serializer used by the view
Method :
- get_serializer_class(self)
Returns the serializer class , Default return serializer_class, Can be rewritten , for example :
def get_serializer_class(self):
if self.request.user.is_staff:
return FullAccountSerializer
return BasicAccountSerializer
- *get_serializer(self, args, kwargs)
Returns the serializer object , Mainly used to provide Mixin Extension classes use , If we want to get the serializer object in the view , You can also call this method directly .
Be careful , When providing a serializer object , Will send the context Attributes add three data :request、format、view, These three data objects can be used when defining a serializer .
- request The request object for the current view
- view The class view object currently requested
- format The data format expected to be returned by the current request
Provide the properties and methods of database query
attribute :
queryset Indicates the data query set to use
Method :
get_queryset(self)
Returns the query set used by the view , Mainly used to provide Mixin Extension classes use , It is the basis of getting data from list view and detail view , Default return queryset attribute , Can be rewritten , for example :
def get_queryset(self):
user = self.request.user
return user.accounts.all()
get_object(self)
Return the model class data object required by the detail view , Mainly used to provide Mixin Extension classes use .
This method can be called in the attempt to get the detailed information of the model class object .
If the model class object for details access does not exist , Returns the 404.
This method is used by default APIView Provided check_object_permissions Whether the method has access to the current object .
give an example :
# url(r'^books/(?P<pk>\d+)/$', views.BookDetailView.as_view()),
class BookDetailView(GenericAPIView):
queryset = BookInfo.objects.all()
serializer_class = BookInfoSerializer
def get(self, request, pk):
book = self.get_object() # get_object() Methods according to the pk Parameter lookup queryset Data objects in
serializer = self.get_serializer(book)
return Response(serializer.data)
Other properties that can be set
- pagination_class Indicates the paging control class
- filter_backends Indicates the filter control backend
2. Five extension classes
effect :
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 call GenericAPIView 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 .
Source code :
class ListModelMixin(object):
""" List a queryset. """
def list(self, request, *args, **kwargs):
# Filter
queryset = self.filter_queryset(self.get_queryset())
# Pagination
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
# serialize
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
give an example :
from demo.models import StudentInfo
from demo.serializers import StudentInfoSerializer
from rest_framework.mixins import ListModelMixin
from rest_framework.generics import GenericAPIView
# Create your views here.
class StudentListView(ListModelMixin, GenericAPIView):
queryset = StudentInfo.objects.all()
serializer_class = StudentInfoSerializer
def get(self, request):
return self.list(request)
result :
2)CreateModelMixin
Create a view extension class , Provide create(request, *args, **kwargs) Method to quickly create a view of resources , Successfully returns 201 Status code .
If the serializer fails to verify the data sent by the front end , return 400 error .
Source code :
class CreateModelMixin(object):
"""
Create a model instance.
"""
def create(self, request, *args, **kwargs):
# Get serializer
serializer = self.get_serializer(data=request.data)
# verification
serializer.is_valid(raise_exception=True)
# preservation
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 {}
give an example :
demo/views.py
from demo.models import StudentInfo, ClassInfo
from demo.serializers import StudentInfoSerializer, ClassInfoSerializer
from rest_framework.mixins import ListModelMixin, CreateModelMixin
from rest_framework.generics import GenericAPIView
class ClassView(CreateModelMixin, GenericAPIView):
queryset = ClassInfo.objects.all()
serializer_class = ClassInfoSerializer
def post(self, request):
return self.create(request)
demo/urls.py
from django.urls import path, include
from demo import views
urlpatterns = [
path('students/', views.StudentListView.as_view()),
path('class/', views.ClassView.as_view()), # Added this sentence
]
result :
3)RetrieveModelMixin
Detail view extension class , Provide retrieve(request, *args, **kwargs) Method , It can quickly return an existing data object .
If there is , return 200, Otherwise return to 404.
Source code :
class RetrieveModelMixin(object):
""" Retrieve a model instance. """
def retrieve(self, request, *args, **kwargs):
# Get objects , The object's permissions are checked
instance = self.get_object()
# serialize
serializer = self.get_serializer(instance)
return Response(serializer.data)
give an example :
from demo.models import StudentInfo, ClassInfo
from demo.serializers import StudentInfoSerializer, ClassInfoSerializer
from rest_framework.mixins import ListModelMixin, CreateModelMixin, RetrieveModelMixin
from rest_framework.generics import GenericAPIView
class ClassView(CreateModelMixin, GenericAPIView, RetrieveModelMixin):
queryset = ClassInfo.objects.all()
serializer_class = ClassInfoSerializer
def post(self, request):
return self.create(request)
# Here are the additions
def get(self, request, pk):
return self.retrieve(request)
add to url:
from django.urls import path, include
from demo import views
urlpatterns = [
path('students/', views.StudentListView.as_view()),
path('class/', views.ClassView.as_view()),
path('class/<int:pk>/', views.ClassView.as_view()), # Added this line
]
result :
4)UpdateModelMixin
Update view extension class , Provide update(request, *args, **kwargs) Method , Can quickly update an existing data object .
It also provides partial_update(request, *args, **kwargs) Method , Local update can be achieved .
Successfully returns 200, When the serializer fails to verify data , return 400 error .
Source code :
class UpdateModelMixin(object):
""" Update a model instance. """
def update(self, request, *args, **kwargs):
partial = kwargs.pop('partial', False)
instance = self.get_object()
serializer = self.get_serializer(instance, data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
if getattr(instance, '_prefetched_objects_cache', None):
# If 'prefetch_related' has been applied to a queryset, we need to
# forcibly invalidate the prefetch cache on the instance.
instance._prefetched_objects_cache = {
}
return Response(serializer.data)
def perform_update(self, serializer):
serializer.save()
def partial_update(self, request, *args, **kwargs):
kwargs['partial'] = True
return self.update(request, *args, **kwargs)
give an example :
from demo.models import StudentInfo, ClassInfo
from demo.serializers import StudentInfoSerializer, ClassInfoSerializer
from rest_framework.mixins import ListModelMixin, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin
from rest_framework.generics import GenericAPIView
class ClassView(CreateModelMixin, GenericAPIView, RetrieveModelMixin, UpdateModelMixin):
queryset = ClassInfo.objects.all()
serializer_class = ClassInfoSerializer
def post(self, request):
return self.create(request)
def get(self, request, pk):
return self.retrieve(request)
# Added the following
def put(self, request, pk):
return self.update(request)
result :
5)DestroyModelMixin
Delete view extension class , Provide destroy(request, *args, **kwargs) Method , It can quickly delete an existing data object .
Successfully returns 204, There is no return 404.
Source code :
class DestroyModelMixin(object):
""" Destroy a model instance. """
def destroy(self, request, *args, **kwargs):
instance = self.get_object()
self.perform_destroy(instance)
return Response(status=status.HTTP_204_NO_CONTENT)
def perform_destroy(self, instance):
instance.delete()
give an example :
from demo.models import StudentInfo, ClassInfo
from demo.serializers import StudentInfoSerializer, ClassInfoSerializer
from rest_framework.mixins import ListModelMixin, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin
from rest_framework.generics import GenericAPIView
class ClassView(CreateModelMixin, GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin):
queryset = ClassInfo.objects.all()
serializer_class = ClassInfoSerializer
def post(self, request):
return self.create(request)
def get(self, request, pk):
return self.retrieve(request)
def put(self, request, pk):
return self.update(request)
# Added the following
def delete(self, request, pk):
return self.destroy(request)
result :
More than a delete Button , After clicking id=1 The data of is deleted 
Next chapter :DRF Learning notes (5): View set ViewSet
边栏推荐
- Enable shallow and deep copies+
- 单机高并发模型设计
- Install MySQL using CentOS yum
- TSMC's counterattack: it accused lattice core of infringing 25 patents and asked for prohibition!
- 43亿欧元现金收购欧司朗宣告失败!ams表示将继续收购
- Excel提取重复项
- Pychart imports the existing local installation package
- Wechat applet personal number opens traffic master
- [sword finger offer] interview question 52: the first common node of two linked lists - stack, hash table, double pointer
- 借5G东风,联发科欲再战高端市场?
猜你喜欢

编码技巧——全局异常捕获&统一的返回体&业务异常

MySQL index

MySQL索引

web测试学习笔记01

keil 采用 makefile 实现编译

Nacos

: 0xc0000005: an access conflict occurs when writing position 0x01458000 - to be solved

Openwrt adds support for SD card

Embedded development: tips and techniques -- seven techniques to meet the real-time deadline

Introduction to JWT
随机推荐
ARIMA模型选择与残差
Web test learning notes 01
借5G东风,联发科欲再战高端市场?
Example of the task submitted by the Flink packer
To meet risc-v challenges? ARM CPU introduces custom instruction function!
Firefox old version
Your password does not satisfy the current policy requirements (modify MySQL password policy setting simple password)
Multiline text overflow dotting
百度图片复制图片地址
微信小程序个人号开通流量主
: 0xC0000005: 写入位置 0x01458000 时发生访问冲突----待解
Openwrt adds RTC (mcp7940 I2C bus) drive details
Nacos
Pychart imports the existing local installation package
Penetration test - dry goods | 80 + network security interview experience post (interview)
web测试学习笔记01
使用transform:translate()出现内容模糊问题
2.2 JMeter基本元件
Test novice learning classic (with ideas)
Pychart import existing project