当前位置:网站首页>General view, DRF view review
General view, DRF view review
2022-07-27 08:32:00 【pink_ Pig___】
1 Preparation for creating a new project
1.1 Create a new project in the command box
Open the specified folder , Enter cmd Open the command line
django-admin startproject Project name Create project
1.2 Create sub applications in new projects
python manage.py startapp Subapplication name
1.3 Register subapplication
stay settings.py Register the sub application in the file
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders', # Configure cross domain
'rest_framework', # To configure drf frame
' The name of the created sub application ' # Register subapplication
]
1.5 Configuration database
stay settings.py In the file
# Configuration database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Use mysql database
'HOST': 'localhost', # host
'PORT': 3306, # port
'USER': 'root', # The user name of the database
'PASSWORD': ' password ', # Database password
'NAME': ' Database name created ', # Database name
}
}
1.6 Modify language and time zone
stay settings.py In the file
LANGUAGE_CODE = 'zh-Hans' # Language
TIME_ZONE = 'Asia/Shanghai' # The time zone
1.7 mount this database
In a folder with the same name as the project name init.py Install
import pymysql
pymysql.install_as_MySQLdb()
1.8 Create model classes
In the sub application folder models.py establish
from django.db import models
# Create your models here.
#BaseModel Parent class
class BaseModel(models.Model):
created_time=models.DateTimeField(auto_now_add=True)
update_time=models.DateTimeField(auto_now=True)
# Departmental table
#name Department name varchar(30)
class Department(BaseModel):
name=models.CharField(' Department name ',max_length=30)
def __str__(self):
return self.name
class Meta:
db_table='tb_department'
# position
class Duty(BaseModel):
name = models.CharField(max_length=30, verbose_name=' Job title ')
def __str__(self):
return self.name
class Meta:
db_table = 'tb_duty'
# staff
class Staff(models.Model):
SEX_CHOICE=(
(1,' male '),
(2,' Woman ')
)
name=models.CharField(' full name ',max_length=20)
sex=models.IntegerField(' Gender ',choices=SEX_CHOICE,default=1)
phone=models.CharField(' cell-phone number ',max_length=11)
email=models.EmailField(max_length=60)
# Foreign keys
department=models.ForeignKey(Department,on_delete=models.CASCADE)
duty=models.ForeignKey(Duty,on_delete=models.CASCADE)
#user
from django.contrib.auth.models import AbstractUser
from django.utils import timezone
class User(AbstractUser):
mobile=models.CharField(' cell-phone number ',max_length=11)
last_login = models.DateTimeField(' Last login time ',default=timezone.now)
def __str__(self):
return self.username
class Meta:
db_table='user'
1.9 After creating the model class, migrate
Execute at the terminal within the project
Generate migration file :python manage.py makemigrations
Perform the migration :python manage.py migrate
If the migration goes wrong , Delete the database and create a new database , The generated migration file is also deleted , Redo the above 2 A step
Fore and aft end separation
The main pursuit of the front end is beauty 、 Fluent 、 compatible
The back-end pursues three high , High performance 、 High concurrency 、 High availability
What is? restful style
Additions and deletions
GET: get data
POST: Submit data , Create data
PUT: Submit data , Update data
DELETE: Delete data
Status code
200 [GET] Status code when obtaining data
201 [POST/PUT/PATCH] Add or create data
204 [DELETE] Status code for deletion
2.DRF engineering
Download third-party modules
Install in the black window
pip install djangorestframework
stay settings.py Registration in file
Cross domain is also done by the way
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',# Cross domain
'myapp',
'rest_framework',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware' # Add cross domain Middleware
]
CORS_ORIGIN_WHITELIST=[
'http://127.0.0.1:8080',
'http://localhost:8080'
]
CORS_ALLOW_CREDENTIALS=True
CORS_ALLOW_METHODS=('*')
CORS_ALLOW_HEADERS=('*')
Serializer automatically gets
Create a serializers.py File write class method
from rest_framework import serializers
# from rest_framework.serializers import ModelSerializer
from .models import *
# Department serializer
class DepartmentSer(serializers.Serializer):
#iabel= Customize the output name after serialization
id=serializers.IntegerField(label='ID',read_only=True)
#trim_whitespace=True Remove the blanks on both sides before saving into the database
name=serializers.CharField(label=' Department name ',min_length=2,max_length=10,allow_null=True,
allow_blank=True,trim_whitespace=True)
class DepartmentSerModelser(serializers.ModelSerializer):
class Meta:
model=Department
fields='__all__'
read_only_fields=['id',]
# Job serializer
class DutySer(serializers.Serializer):
id = serializers.IntegerField(label='ID', read_only=True)
name = serializers.CharField(label=' Job title ', min_length=2, max_length=10, allow_null=True,
allow_blank=True, trim_whitespace=True)
class DutySerModelser(serializers.ModelSerializer):
class Meta:
model=Duty
fields='__all__'
read_only_fields=['id',]
from rest_framework.exceptions import ValidationError
# Serializer for employees
class StaffSer(serializers.Serializer):
id = serializers.IntegerField(label='ID', read_only=True)
name = serializers.CharField(label=' Employee name ', min_length=2, max_length=10, allow_null=True,
allow_blank=True, trim_whitespace=True)
sex =serializers.IntegerField(label=' Gender ',default=1)
phone=serializers.CharField(label=' cell-phone number ',min_length=11,max_length=11,allow_null=True,allow_blank=True,)
# email=serializers.CharField(label=' mailbox ',max_length=60)
# Foreign keys
department=serializers.PrimaryKeyRelatedField(queryset=Department.objects.all())
duty=serializers.PrimaryKeyRelatedField(queryset=Duty.objects.all())
# Serialized method fields
department_name=serializers.SerializerMethodField(read_only=True)
def get_department_name(self,obj):
return obj.department.name
duty_name=serializers.SerializerMethodField(read_only=True)
def get_duty_name(self,obj):
return obj.duty.name
# data verification
def validate(self, attrs):
# get data
name=attrs.get('name')
...
phone=attrs.get('phone')
# Check the data
if not phone.startswith('17'):
raise ValidationError(' The mobile phone number does not comply with the rules ')
return attrs
# rewrite create Method
def create(self, validated_data):
# ** Unpack
staff=Staff.objects.create(**validated_data)
return staff
# rewrite uodate Method
def update(self, instance, validated_data):
# Add the field name if you want to modify something
instance.name=validated_data.get('name')
instance.phone=validated_data.get('phone')
instance.save()
return instance
class StaffModelser(serializers.ModelSerializer):
class Meta:
model=Staff
fields='__all__'
read_only_fields=['id',]
The concept of view set mixed with classes
stay ModelViewSet Inherit from class GenericAPIView, It is also used in various action implementations , Through the behavior of various mixed classes , Contains .list、.retrieve、.create、.update、.partial_update、 and .destroy Other methods , Inherit ListModelMixin、RetrieveModelMixin、CreateModelMixin、UpdateModelMixin、DestroyModelMixin
drf Additions and deletions
The common method is to add, check and change
from rest_framework.views import APIView
from rest_framework.response import Response
from users.models import BaseModel,Department,Duty,Staff
from users.serializers import StaffSer
class Staffview(APIView):
def get(self,request):
# Check all employees
stf_all=Staff.objects.all()
# serialize , Return a serializer object
ser=StaffSer(stf_all,many=True)
return Response(ser.data)
def post(self,request):
name=request.data.get('name')
# Query the employee object according to the user name
staff=Staff.objects.filter(name=name)
if staff:
return Response({
'code':400,'msg':' Employee already exists '})
# Employees can be added normally if they do not exist # Deserialization
ser=StaffSer(data=request.data)
# data verification
if ser.is_valid(raise_exception=True):
# Save the data
ser.save() #create Method
return Response({
'code':200,'msg':' Add employee successfully '})
else:
return Response({
'code':400,'msg':ser.errors})
# Employee details
class Staffview2(APIView):
#orm Query individual data
def get(self,request,pk):
try:
sta_data=Staff.objects.get(id=pk)
except Exception as a:
return Response({
'msg':' Employees don't exist '})
# Yes ORM Operate the queried data to serialize q
ser=StaffSer(sta_data)
return Response(ser.data)
def put(self,request,pk):
# Query the updated object
staff=Staff.objects.filter(id=pk).first()
# Deserialization to update # Partial update
# instance The object to be modified
# data Data to be modified
# partial=True Modify all by default , by True when , Some fields can be modified
ser=StaffSer(instance=staff,data=request.data,partial=True)
# Check the data
if ser.is_valid():
ser.save() #update
return Response({
'code':200,'msg':' The update is successful '})
else:
return Response({
'code':400,'msg':ser.errors})
def delete(self,request,pk):
return Response({
'code':200,'msg':' Delete employee succeeded '})
GenericAPIView Use Mix in extension classes
GenericAPIView Inherited from APIVIew, Added common support methods for list view and detail view , Can be paired with one or more Mixin The extension class , To achieve other more advanced functions .
from rest_framework.response import Response
from rest_framework.generics import *
from rest_framework.mixins import *
rom users.models import BaseModel,Department,Duty,Staff
from users.serializers import StaffSer,StaffModelser
# Look at employees
class Staffview(GenericAPIView,ListModelMixin,CreateModelMixin):
queryset = Staff.objects.all()
serializer_class = StaffSer
def get(self,request,*args,**kwargs):
return self.list(request,*args,**kwargs)
def post(self,request,*args,**kwargs):
return self.create(request,*args,**kwargs)
# Employee details
class Staffview2(GenericAPIView,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin):
queryset = Staff.objects.all()
serializer_class = StaffSer
#orm Query individual data
def get(self,request,pk):
try:
sta_data=Staff.objects.get(id=pk)
except Exception as a:
return Response({
'msg':' Employees don't exist '})
ser=StaffSer(sta_data)
return Response(ser.data)
def put(self,request,pk):
return self.update(request,pk)
def delete(self,request,pk):
return self.destroy(request.pk)
Subclass view
notes : Subclass views are in from rest_framework.generics Module .
from rest_framework.generics import *
from users.models import BaseModel,Department,Duty,Staff
from users.serializers import StaffSer,StaffModelser
# View employees and add employees
class Staffview(ListCreateAPIView):
queryset = Staff.objects.all()
serializer_class = StaffSer
# Employee details , Modify employees , Delete employee
class Staffview2(RetrieveUpdateDestroyAPIView):
queryset = Staff.objects.all()
serializer_class = StaffSer
lookup_field = 'pk'
lookup_url_kwarg = 'pk'
Configure the routing
from django.urls import path
from users import views
urlpatterns = [
# path('admin/', admin.site.urls),
# View all employees
path('staffs/',views.Staffview.as_view()),
# Employee details
path('staffs/<int:pk>/',views.Staffview2.as_view())
]
View set implementation
What is a view set
View set is simply a group of view logic operations Function collection , And... Can be used Route mapping Function selection in different ways , The built-in logical methods written are no longer named with requests , Instead, use functions to name
from rest_framework.viewsets import ModelViewSet
from users.models import BaseModel,Department,Duty,Staff
from users.serializers import StaffSer,StaffModelser
# View set
class Staffview(ModelViewSet):
queryset = Staff.objects.all()
serializer_class = StaffSer
Configure the routing
from django.urls import path
from users import views
from rest_framework import routers
urlpatterns = [
]
# Generate routing object
router=routers.SimpleRouter()
#2. Generate a route using a route object
# Parameters 1: Name of the path 2: View set used 3: Give the generated route a name
router.register('staffs',views.Staffview,'staffs')
#3. Route append
urlpatterns+=router.urls
边栏推荐
- Interviewer: what is scaffolding? Why do you need scaffolding? What are the commonly used scaffolds?
- MCDF top level verification scheme
- openGauss之TryMe初体验
- You may need an additional loader to handle the result of these loaders.
- 2022/7/26 exam summary
- docker 安装mysql后进入容器内部发现登录不了mysql
- Flask one to many database creation, basic addition, deletion, modification and query
- SSTI template injection
- Realization of specification management and specification option management functions
- Help send some recruitment. If you are interested, you can have a look
猜你喜欢
![[NPUCTF2020]ReadlezPHP 1](/img/d9/590446b45f917be3f077a9ea739c20.png)
[NPUCTF2020]ReadlezPHP 1

Hundreds of people participated. What are these people talking about in the opengauss open source community?

Virtual machine cloning

Apache SSI remote command execution vulnerability

"PHP Basics" tags in PHP
![[geek challenge 2019] finalsql 1](/img/a7/857d47639fcb38e0055a2444206b8c.png)
[geek challenge 2019] finalsql 1

idea远程调试

Eval and assert execute one sentence Trojan horse

After downloading URL loader and specifying the size of the image with limit, the image will not be displayed

Solution to the program design of the sequence structure of one book (Chapter 1)
随机推荐
After installing mysql, docker entered the container and found that he could not log in to MySQL
You may need an additional loader to handle the result of these loaders.
QT creator code style plug-in beautifier
JS rotation chart
Redis configuration file download
Day3 -- flag state holding, exception handling and request hook
VS Code中#include报错(新建的头文件)
Day6 --- Sqlalchemy advanced
Alibaba cloud international receipt message introduction and configuration process
JS advanced knowledge - function
情人节,我用字符画出了一个对象!
regular expression
Netdata 性能监测工具介绍、安装、使用
Login to homepage function implementation
containerd拉取私库镜像失败(kubelet)
[netding cup 2020 rosefinch group]nmap 1 two solutions
Attack and defense World Lottery
All in one 1251 - Fairy Island for medicine (breadth first search)
Demo:st05 find text ID information
Openresty + keepalived 实现负载均衡 + IPV6 验证