回顾
请求(APIView源码,Requset对象)和响应(Response,自己封装Response),
序列化,
视图,
路由,
解析器(DEFAULT_PARSER_CLASSES,全局配置,局部配置),
响应器(DEFAULT_RENDERER_CLASSES,全局配,局部配),
认证:校验是否登录(有内置,自定义,全局配置,局部配置)
权限:是否有权限访问某些接口(有内置,自定义,全局配置,局部配置)
频率:限制访问频次(有内置,自定义,全局配置,局部配置),根据用户ip,根据用户id限制
过滤:筛选,查询出符合条件的
排序:结果进行排序
异常:全局异常(自定义,全局配置)
版本控制(不讲)
分页器
文档生成
jwt认证
Xadmin的使用
路飞项目
git
redis
短信
支付宝支付
今日内容
1 books系列表接口
from django.urls import path,re_path
from api import views
urlpatterns = [
path('books/', views.BookAPIView.as_view()),
re_path('books/(?P<pk>d+)', views.BookAPIView.as_view()),
]
from rest_framework.response import Response
from api import models
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from api.ser import BookModelSerializer
class BookAPIView(APIView):
def get(self,request,*args,**kwargs):
book_list=models.Book.objects.all().filter(is_delete=False)
book_list_ser=BookModelSerializer(book_list,many=True)
return Response(data=book_list_ser.data)
def post(self,request,*args,**kwargs):
if isinstance(request.data,dict):
book_ser=BookModelSerializer(data=request.data)
book_ser.is_valid(raise_exception=True)
book_ser.save()
return Response(data=book_ser.data)
elif isinstance(request.data,list):
from rest_framework.serializers import ListSerializer
book_ser = BookModelSerializer(data=request.data,many=True)
print('--------',type(book_ser))
book_ser.is_valid(raise_exception=True)
book_ser.save()
return Response(data=book_ser.data)
def put(self,request,*args,**kwargs):
if kwargs.get('pk',None):
book=models.Book.objects.filter(pk=kwargs.get('pk')).first()
book_ser = BookModelSerializer(instance=book,data=request.data,partial=True)
book_ser.is_valid(raise_exception=True)
book_ser.save()
return Response(data=book_ser.data)
else:
book_list=[]
modify_data=[]
for item in request.data:
pk=item.pop('id')
book=models.Book.objects.get(pk=pk)
book_list.append(book)
modify_data.append(item)
book_ser = BookModelSerializer(instance=book_list,data=modify_data,many=True)
book_ser.is_valid(raise_exception=True)
book_ser.save()
return Response(book_ser.data)
def delete(self,request,*args,**kwargs):
pk=kwargs.get('pk')
pks=[]
if pk:
pks.append(pk)
else:
pks=request.data.get('pks')
ret=models.Book.objects.filter(pk__in=pks,is_delete=False).update(is_delete=True)
if ret:
return Response(data={'msg':'删除成功'})
else:
return Response(data={'msg': '没有要删除的数据'})
ser.py
from rest_framework import serializers
from api import models
class BookListSerializer(serializers.ListSerializer):
def update(self, instance, validated_data):
print(instance)
print(validated_data)
return [
self.child.update(instance[i],attrs) for i,attrs in enumerate(validated_data)
]
class BookModelSerializer(serializers.ModelSerializer):
class Meta:
list_serializer_class=BookListSerializer
model=models.Book
fields = ('name','price','authors','publish','publish_name','author_list')
extra_kwargs={
'publish':{'write_only':True},
'publish_name':{'read_only':True},
'authors':{'write_only':True},
'author_list':{'read_only':True}
}
from django.db import models
from django.contrib.auth.models import AbstractUser
class BaseModel(models.Model):
is_delete=models.BooleanField(default=False)
create_time=models.DateTimeField(auto_now_add=True)
last_update_time=models.DateTimeField(auto_now=True)
class Meta:
abstract=True
class Book(BaseModel):
id=models.AutoField(primary_key=True)
name=models.CharField(max_length=32,verbose_name='书名',help_text='这里填书名')
price=models.DecimalField(max_digits=5,decimal_places=2)
publish=models.ForeignKey(to='Publish',on_delete=models.DO_NOTHING,db_constraint=False)
authors=models.ManyToManyField(to='Author',db_constraint=False)
class Meta:
verbose_name_plural='书表'
def __str__(self):
return self.name
@property
def publish_name(self):
return self.publish.name
def author_list(self):
author_list=self.authors.all()
return [ {'name':author.name,'sex':author.get_sex_display()}for author in author_list]
class Publish(BaseModel):
name = models.CharField(max_length=32)
addr=models.CharField(max_length=32)
def __str__(self):
return self.name
class Author(BaseModel):
name=models.CharField(max_length=32)
sex=models.IntegerField(choices=((1,'男'),(2,'女')))
authordetail=models.OneToOneField(to='AuthorDetail',db_constraint=False,on_delete=models.CASCADE)
class AuthorDetail(BaseModel):
mobile=models.CharField(max_length=11)
2 分页器
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination,LimitOffsetPagination,CursorPagination
'''
PageNumberPagination
page_size:每页显示的条数
'''
class MyPageNumberPagination(PageNumberPagination):
page_size=3
page_query_param='aaa'
page_size_query_param='size'
max_page_size=5
class MyCursorPagination(CursorPagination):
cursor_query_param = 'cursor'
page_size = 2
ordering = '-id'
from utils.throttling import MyThrottle
class BookView(APIView):
def get(self,request,*args,**kwargs):
book_list=models.Book.objects.all()
page_cursor=MyPageNumberPagination()
book_list=page_cursor.paginate_queryset(book_list,request,view=self)
next_url =page_cursor.get_next_link()
pr_url=page_cursor.get_previous_link()
book_ser=BookModelSerializer(book_list,many=True)
return Response(data=book_ser.data)
REST_FRAMEWORK={
'PAGE_SIZE': 2,
}
3 根据ip进行频率限制
from rest_framework.throttling import ScopedRateThrottle,SimpleRateThrottle
class MyThrottle(SimpleRateThrottle):
scope='luffy'
def get_cache_key(self, request, view):
print(request.META.get('REMOTE_ADDR'))
return request.META.get('REMOTE_ADDR')
REST_FRAMEWORK={
'DEFAULT_THROTTLE_CLASSES': (
'utils.throttling.MyThrottle',
),
'DEFAULT_THROTTLE_RATES': {
'luffy': '3/m'
},
}
作业
1 一个表可不可以有多个自增字段
2 用GenericAPIView重写book的单增,群增,。。。。