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

Note: Django rest framework view

編輯:Python

1, Write a first APP, Name is dsj

1.1 urls.py The contents of the document are as follows :

from django.urls import path, re_path, include
from django.conf.urls import url
from . import views
# The following is to use rest framework The routing system is set 
from rest_framework import routers
router = routers.DefaultRouter() # Instantiate a default class 
router.register(prefix=r'xxx', viewset=views.V3View) # Register in the system , Note the parameters here ,prefix Prefix means , Generated url There will be this ,viewset Which view you want to register , Here is V3View
router.register(prefix=r'rt', viewset=views.V3View) # There's nothing wrong here , Because the prefix is different , Generated url Is different . Register in the system , Note the parameters here ,prefix Prefix means , Generated url There will be this ,viewset Which view you want to register , Here is V3View
# How to verify the above routing settings , And the following settings , As long as we are url Misspelled in , Then it will report many wrong routes , You can see whether there is an automatically generated route url
urlpatterns = [
re_path(r'^roles/$', views.RolesView.as_view()),
re_path(r'^userinfo/$', views.UserInfoView.as_view()),
re_path(r'^group/(?P<pk>\d+)$', views.GroupView.as_view(), name='gp'), # Notice the pk, It is written in the default system , Can be in view To get rid of ., The source code in : class HyperlinkedRelatedField(RelatedField): lookup_field = 'pk' This pk That's what people default on pk, however pk incorrect , because pk yes id,id It is changing. , Two groups are fixed .
re_path(r'^usergroup/$', views.UserGroupView.as_view()),
re_path(r'^page1/$', views.Page1View.as_view()), # This is when testing the paging function URL
re_path(r'^page2/$', views.Page1View_2.as_view()), # This is when testing the paging function URL
re_path(r'^page3/$', views.Page1View_3.as_view()), # This is when testing the paging function URL
re_path(r'^v1/$', views.V1View.as_view()), # This is the test restframework View View function URL
re_path(r'^v2/$', views.V2View.as_view({
'get': 'xxx'})), # here V2View() Inherited GenericViewSet, This class overrides as_view() Method , Delivery required action Method 
# here V3View() Inherited ModelViewSet, ModelViewSet And inherited GenericViewSet(), then GenericViewSet Rewrote as_view() Method , So our customized class view inherits ModelViewSet() class 
# Also rewrite url Medium as_view(), Pass him parameters .
# First of all, this one-to-one correspondence requires querying the source code , There are specific function names in the source code .
re_path(r'^v3/$', views.V3View.as_view({
'get': 'list', 'post':'create'})), # Pay attention to this url First half of , Didn't write that pk, What do you mean , Express get All the data is requested ,post The request does not need to be specified pk, You can directly pass the corresponding fields to the database ,
# Note the following url, This one's inside pk\d+ It refers to a data in the database , It is no longer a whole , Operate on a data , Look at the corresponding methods . Remember not to make mistakes . You can realize the function of adding, deleting, modifying and checking one by one 
re_path(r'^v3/(?P<pk>\d+)/$', views.V3View.as_view({
'get': 'retrieve', 'delete':'destroy', 'put':'update', 'patch':'partial_update'})),
#'''
# The following code is the routing system , Automatically generated routes 
# Why should the system automatically generate url, Because for a view , Tend to have 2 individual url, Because it is the reason to obtain the overall and individual data , Then add json Format reason , There will be one 
# The view generates 4 individual url, Then if you think it's troublesome to write , You can set some here , Let the system help you generate 
#'''
# url(r'(?P<version>)[v1|v2]/$', include(router.urls)), Writing with version prefix .
url(r'^', include(router.urls)), # You have to use it here url(),re_path and path no way .
# Below url It is used to test the renderer 
url(r'^test/$', views.TestView.as_view())
]

1.2 models.py The contents of the document are as follows , New data table

from django.db import models
class UserInfo(models.Model):
user_type_choices = (
(1, ' Ordinary users '),
(2, 'VIP Customer '),
(3, 'SVIP')
)
user_type = models.IntegerField(choices=user_type_choices)
username = models.CharField(max_length=32, unique=True)
password = models.CharField(max_length=64)
group = models.ForeignKey(to='UserGroup', on_delete=models.CASCADE) # Suppose a group corresponds to multiple people , One person only has multiple groups 
roles = models.ManyToManyField('Role')
class UserGroup(models.Model):
title = models.CharField(max_length=32)
class Role(models.Model):
title = models.CharField(max_length=32)

1.3 views.py Documentation , Write serializer Serialization and deserialization

#######################django rest framework View function #############################################
''' Say directly in one step , The inheritance relationship in this view class , The further down, the more functions are inherited , And the system also helps us to realize based on view Addition, deletion and modification of , It's all based on mixin Class operation of , The following total price : Inheritance chain 1: 1, View -> APIView -> GenericAPIView -> [CreateAPIView(mixins.CreateModelMixin, GenericAPIView), ListAPIView, RetrieveAPIView, DestroyAPIView, UpdateAPIView, ListCreateAPIView, RetrieveUpdateAPIView, RetrieveDestroyAPIView, RetrieveUpdateDestroyAPIView] Inheritance chain 2: 2, View -> APIView -> GenericAPIView -> GenericViewSet(ViewSetMixin, generics.GenericAPIView) -> class ModelViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, mixins.ListModelMixin, GenericViewSet) actually ,2 An inheritance chain , Inherit to the end , Each of them has realized , Function of adding, deleting, modifying and checking , But the way of implementation is class or Mixin The way , And there is also a one-to-one correspondence here , Rewrite the get, post put, patch Of , Make these ordinary ways corresponding , List, create, update, delete And the corresponding class or Mixin. After rewriting here , Similarly, we need to change that url in path, because get, post. The corresponding function cannot be found , So in url Medium as_view() Function , You need to fill in the corresponding parameters , One by one , for instance : get->list, post->create, put->update And other parameters are passed in the way of dictionary . meanwhile path Inside url Two to write , One makes for the whole , One is for one of the whole , for instance : re_path(r'^viewtest/$', ViewTest.as_view({'get':'list', 'post':'create'}) -> This is for the entire database re_path(r'^viewtest/(?P<pk>\d+)/$', ViewTest.as_view({'get':'retrieve', 'delete':'destroy', 'put':'update', 'patch':'partial_update'}) -> This is for a separate data operation in the database , You can see (?P<pk>\d+) This is a separate instance operation . Use ModelViewSet() This class ,URL It can also automatically generate , Namely rest framework Even this part is done for us , It's really the basic framework of nanny . '''
# 1, Following example GenericAPIView: Unpractical 
from rest_framework.generics import GenericAPIView # View source code , You can see GenericAPIView Inherit what we have been writing before APIView()
''' This GenericAPIView() It's full of get_ Method , These methods It's all about serialization before implementation , Paging function , It's just that it's all made up of its own fields , This class It's actually not easy to use , No more than what we wrote alone before serializer() class , pagination() class , Instantiate it yourself , Paging is easy , So this can be dispensed with , It's better to inherit APIView '''
class V1View(GenericAPIView):
def get(self, request, *args, **kwargs):
return Response()
# 2, Following example GenericViewSet
from rest_framework.viewsets import GenericViewSet # Look at the source code , This class overrides as_view() Method , And you need to pass parameters in , So that URL You can understand it by passing parameters in , one-on-one get->list, post->create etc. . Or map to the written in the system Mixin Method .
class V2View(GenericViewSet):
# It's inherited here GenericViewSet Rewrote as_view() Method , So in url Pass on the reference , Delivery dictionary , yes get->list, And then this list Also write one here list function . Of course, here it is list The name can be changed , You can change to xxx, meanwhile url The corresponding dictionary in should also be changed into xxx
def xxx(self, request, *args, **kwargs):
return Response('xx')
# 3, Following example ModelViewSet
from rest_framework.viewsets import ModelViewSet # Look at the source code. This class inherits a lot Mixin And the above GenericViewSet(), So it inherits all the methods above , At the same time, there are many things that need to be set 
class Page_3Serializer(serializers.ModelSerializer):
class Meta:
model = Role
fields = "__all__"
class V3View(ModelViewSet):
''' This class inherits ModelViewSet(), ModelViewSet() And inherited a lot Mixin and GenericViewSet(), So according to the source code Here we just need to set : The data sheet we want to operate , That's it. queryset To serialize that data table , That's it. serializer_class Which paging class to use , That's it. pagination_class These are the three properties set below . As long as the following three properties are set , And then in url in , Write the method you want Corresponding Dictionary , You can complete the basic operations of adding, deleting, modifying and querying . '''
queryset = Role.objects.all()
serializer_class = Page_3Serializer
pagination_class = PageNumberPagination
''' Part summary : If you want more and more functions , When you can customize the view , Inherit downward , such as ModelViewSet() This has many functions , What has . If you want to realize some functions of adding, deleting, modifying and checking by yourself , You inherit APIView(), This is closer View class , You need to realize many functions by yourself Here, please pay attention to : Here is an example 3, Inherited ModelViewSet() So please pay attention url Where to start with the object method name , The second is to write two views in one view URL, One is for the whole One is for one data . If you don't inherit this class , So how to distinguish the incoming requests from the front end , such as get request , Is it for the whole or a data , Need to be in kwargs Inside judgment If it's delivered id Then it's a data , If there is no transmission , Then it's the whole . Summary of scope of use : a, Want to add, delete, modify and check : Inherit ModelViewSet() b, Want to add or delete : Inherit CreateModelMixin, DestroyModelMixin, GenericViewSet c, Want complex logic : Inherit GenericViewSet or APIView The following is about the routing system URL Summarize together . '''
#########View###### View ####### end 

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