用drf编写
'''
1 有车型(CarModel),车厂(CarFactory),经销商(Distributor)三个表,
一个车厂可以生产多种车型,一个经销商可以出售多种车型,一个车型可以有多个经销商出售
车型:车型名,车型出厂价,车厂id
车厂:车厂名,车厂地址,联系电话
经销商:经销商名,地址,联系电话
2 有用户表,基于django内置user表,扩展mobile字段
3 编写登陆接口,jwt方式返回token,
格式为{status:100,msg:登陆成功,token:safasdfa}
4 所有接口(除登录外),必须登录后才能访问
5 管理员登陆后可以增,删,单查,群查,改 车型,车厂,经销商(具备所有接口权限)
6 普通用户登陆可以查看车型,车厂,经销商单条,所有(只有查看权限)
7 所有查询所有接口带分页功能
8 查询所有车型接口,可以按车型名字精准过滤
加分项:
用户注册接口
管理员有用户锁定,删除用户功能
'''
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
models.py
from django. db import models
from django. contrib. auth. models import AbstractUser
class User ( AbstractUser) :
mobile = models. CharField( max_length= 32 , verbose_name= '联系电话' )
class CarModel ( models. Model) :
name = models. CharField( max_length= 32 , verbose_name= '车型名' )
init_price = models. IntegerField( verbose_name= '出厂价' )
factory = models. ForeignKey( to= 'CarFactory' , on_delete= models. CASCADE, verbose_name= '车厂id' )
distributors = models. ManyToManyField( to= 'Distributor' , verbose_name= '经销商' )
class Meta :
verbose_name_plural = '经销商表'
def __str__ ( self) :
return self. name
def factory_info ( self) :
'''
车厂信息
'''
return { 'name' : self. factory. name, 'addr' : self. factory. addr, 'mobile' : self. factory. mobile}
def distributor_info ( self) :
'''
经销商信息
'''
distributor_info_list = [ ]
for distributor in self. distributors. all ( ) :
distributor_info_list. append( { 'name' : distributor. name, 'addr' : distributor. addr,
'mobile' : distributor. mobile} )
return distributor_info_list
class CarFactory ( models. Model) :
name = models. CharField( max_length= 32 , verbose_name= '车厂名' )
addr = models. CharField( max_length= 32 , verbose_name= '车厂地址' )
mobile = models. CharField( max_length= 32 , verbose_name= '联系电话' )
class Meta :
verbose_name_plural = '经销商表'
def __str__ ( self) :
return self. name
class Distributor ( models. Model) :
name = models. CharField( max_length= 32 , verbose_name= '经销商名' )
addr = models. CharField( max_length= 32 , verbose_name= '地址' )
mobile = models. CharField( max_length= 32 , verbose_name= '联系电话' )
class Meta :
verbose_name_plural = '经销商表'
def __str__ ( self) :
return self. name
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
新建一个jwt_response.py验证登录
def jwt_response_payload_handler ( token, user, request) :
return {
'code' : 100 ,
'msg' : '登录成功' ,
'token' : token
}
新建一个exceptions.py验证错误
from rest_framework. views import exception_handler
from rest_framework. response import Response
def common_exception ( exc, context) :
res = exception_handler( exc, context)
if not res:
return Response( { 'code' : 999 , 'msg' : f'非drf错误,错误信息是: { str ( exc) } ' } )
return Response( { 'code' : 666 , 'msg' : f'这是drf错误,错误信息是: { res. data. get( "detail" ) } ' } )
settings.py配置文件中
JWT_AUTH = {
'JWT_RESPONSE_PAYLOAD_HANDLER' : 'app01.jwt_response.jwt_response_payload_handler' ,
'JWT_EXPIRATION_DELTA' : datetime. timedelta( days= 1 )
}
REST_FRAMEWORK = {
'EXCEPTION_HANDLER' : 'app01.exceptions.common_exception' ,
}
新建page.py分页
from rest_framework. pagination import PageNumberPagination
class MyPageNumberPagination ( PageNumberPagination) :
page_size = 3
max_page_size = 5
新建serializer.py分页
from rest_framework import serializers
from app01. models import User, CarModel, CarFactory, Distributor
class UserSerializer ( serializers. ModelSerializer) :
class Meta :
model = User
fields = [ 'username' , 'password' , 'mobile' ]
extra_kwargs = {
'password' : { 'write_only' : True }
}
def create ( self, validated_data) :
user = User. objects. create_user( ** validated_data)
return user
class CarModelSerializer ( serializers. ModelSerializer) :
class Meta :
model = CarModel
fields = [ 'id' , 'name' , 'init_price' , 'factory' , 'distributors' , 'factory_info' , 'distributor_info' ]
extra_kwargs = {
'factory' : { 'write_only' : True } ,
'distributors' : { 'write_only' : True } ,
'factory_info' : { 'read_only' : True } ,
'distributor_info' : { 'read_only' : True } ,
}
class CarFactorySerializer ( serializers. ModelSerializer) :
class Meta :
model = CarFactory
fields = '__all__'
class DistributorSerializer ( serializers. ModelSerializer) :
class Meta :
model = Distributor
fields = '__all__'
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
新建permission.py权限
from rest_framework. permissions import BasePermission
from rest_framework. exceptions import AuthenticationFailed
class MyPermission ( BasePermission) :
def has_permission ( self, request, view) :
print ( view. action)
if not request. user. is_superuser and request. method != 'GET' :
raise AuthenticationFailed( '普通用户,权限不足' )
return True
views.py视图中
from rest_framework. viewsets import ViewSet
from rest_framework. generics import GenericAPIView
from rest_framework. mixins import CreateModelMixin
from . models import User
from . serializer import UserSerializer
from rest_framework. response import Response
class UserView ( ViewSet, GenericAPIView, CreateModelMixin) :
queryset = User. objects. all ( )
serializer_class = UserSerializer
def create ( self, request, * args, ** kwargs) :
ser = self. get_serializer( data= request. data)
if ser. is_valid( ) :
ser. save( )
return Response( { 'code' : 100 , 'msg' : '注册成功' , 'result' : ser. data} )
return Response( { 'code' : 101 , 'msg' : '注册失败' , 'result' : ser. errors} )
from rest_framework. mixins import DestroyModelMixin
from rest_framework_jwt. authentication import JSONWebTokenAuthentication
from rest_framework. permissions import IsAuthenticated, IsAdminUser
from rest_framework. decorators import action
class AdminView ( ViewSet, GenericAPIView, DestroyModelMixin) :
queryset = User. objects. all ( )
authentication_classes = [ JSONWebTokenAuthentication]
permission_classes = [ IsAuthenticated, IsAdminUser]
@action ( methods= [ 'DELETE' ] , detail= True )
def delete_user ( self, request, * args, ** kwargs) :
return self. destroy( request, * args, ** kwargs)
@action ( methods= [ 'GET' ] , detail= True )
def lock ( self, request, * args, ** kwargs) :
user = self. get_object( )
if user is None :
return Response( { 'code' : 101 , 'msg' : '用户不存在' } )
if user. is_active:
user. is_active = False
user. save( )
return Response( { 'code' : 100 , 'msg' : '用户锁定成功' } )
return Response( { 'code' : 102 , 'msg' : '用户已经被锁定' } )
@action ( methods= [ 'GET' ] , detail= True )
def unlock ( self, request, * args, ** kwargs) :
user = self. get_object( )
if user is None :
return Response( { 'code' : 101 , 'msg' : '用户不存在' } )
if user. is_active is False :
user. is_active = True
user. save( )
return Response( { 'code' : 100 , 'msg' : '用户解锁成功' } )
return Response( { 'code' : 102 , 'msg' : '用户已经解锁过了' } )
from rest_framework. viewsets import ModelViewSet
from . models import CarModel
from . serializer import CarModelSerializer
from . permissions import MyPermission
from . page import MyPageNumberPagination
from django_filters. rest_framework import DjangoFilterBackend
class CarModelView ( ModelViewSet) :
queryset = CarModel. objects. all ( )
serializer_class = CarModelSerializer
authentication_classes = [ JSONWebTokenAuthentication]
permission_classes = [ IsAuthenticated, MyPermission]
pagination_class = MyPageNumberPagination
filter_backends = [ DjangoFilterBackend]
filterset_fields = [ 'name' ]
from . models import CarFactory
from . serializer import CarFactorySerializer
class CarFactoryView ( ModelViewSet) :
queryset = CarFactory. objects. all ( )
serializer_class = CarFactorySerializer
pagination_class = MyPageNumberPagination
authentication_classes = [ JSONWebTokenAuthentication]
permission_classes = [ IsAuthenticated, MyPermission]
from . models import Distributor
from . serializer import DistributorSerializer
class DistributorView ( ModelViewSet) :
queryset = Distributor. objects. all ( )
serializer_class = DistributorSerializer
pagination_class = MyPageNumberPagination
authentication_classes = [ JSONWebTokenAuthentication]
permission_classes = [ IsAuthenticated, MyPermission]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
urls.py路由中
from django. contrib import admin
from django. urls import path, include
from rest_framework_jwt. views import obtain_jwt_token
from rest_framework. routers import SimpleRouter
from app01. views import UserView, AdminView, CarModelView, CarFactoryView, DistributorView
router = SimpleRouter( )
router. register( 'user' , UserView, 'user' )
router. register( 'admin' , AdminView, 'admin' )
router. register( 'carMode' , CarModelView, 'carMode' )
router. register( 'carFactory' , CarFactoryView, 'carFactory' )
router. register( 'distributor' , DistributorView, 'distributor' )
urlpatterns = [
path( 'login/' , obtain_jwt_token) ,
path( '' , include( router. urls) )
]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26