标签:def res params mode generics 地址 set request xxx
from rest_framework.request import Resquest
# 在Resuquest中,对原生request进行了一次封装,self._request = request
def __getattr__(self, item):
return getattr(self._request, item)
# 请求对象.data中存放的就是三种编码方式传入的数据,都可以取出来
# 请求对象.query_params 效果等同于django标准的request.GET相同。
#from rest_framework.response import Response
def __init__(self, data=None, status=None,
template_name=None, headers=None,
exception=False, content_type=None):
‘‘‘
Response类中的init进行解析:
data:要返回的数据,字典
status:返回的状态码 默认是200
from rest_framework import status中存放的是所有用到的状态码是常量。
template_name: 渲染的模板名字,有默认的模板,也可以自己定制
headers:响应头,可以向响应头中放东西。字典
content_type:响应的编码格式:application/json或text/html
通过浏览器响应会有一个模板文件返回,而postman发出请求返回的是json格式数据,这是通过配置实现的。
‘‘‘
# 如果把第二个浏览器渲染器注释掉,那么都会返回Json格式数据。
# 也可以设置生效范围
# 局部使用:只针对某个视图类使用
from rest_framework.renderers import JSONRenderer
renderer_classes=[JSONRenderer,]
# 也可以设置全局使用
REST_FRAMEWORK = {
‘DEFAULT_RENDERER_CLASSES‘: ( # 默认响应渲染类
‘rest_framework.renderers.JSONRenderer‘, # json渲染器
‘rest_framework.renderers.BrowsableAPIRenderer‘, # 浏览API渲染器
)
}
两个视图基类:
# views.py
from rest_framework.generics import GenericAPIView
from app01.models import Book
from app01.ser import BookSerializer
# 基于APIView写的
class BooksView(APIView):
def get(self, request):
response_dict = Response_dict()
book_list = models.Book.objects.all()
book_ser = BookModelSerializer(instance=book_list, many=True)
response_dict.data = book_ser.data
return Response(response_dict.dic)
def post(self, request):
book_ser = BookModelSerializer(data=request.data)
response_dict = Response_dict()
if book_ser.is_valid():
book_ser.save()
response_dict.data = book_ser.data
else:
response_dict.status = 201
response_dict.msg = ‘凉凉‘
response_dict.data = book_ser.errors
return Response(response_dict.dic)
class BookView(APIView):
def get(self,request, pk):
book_obj = models.Book.objects.filter(pk=pk).first()
book_ser = BookModelSerializer(instance=book_obj)
response_dict = Response_dict()
response_dict.data = book_ser.data
return Response_dict(response_dict.dic)
def put(self, request, pk):
response_dict = Response_dict()
book_obj = models.Book.objects.filter(pk=pk).first()
book_ser = BookModelSerializer(instance=book_obj, data=request.data)
if book_ser.is_valid():
book_ser.save()
response_dict.data = book_obj
else:
response_dict.status = 202
response_dict.msg = ‘数据校验出问题啦‘
response_dict.data = book_ser.errors
return Response(response_dict.dic)
def delete(self, request, pk):
models.Book.objects.filter(pk=pk).delete()
response_dict = Response_dict()
return Response(response_dict.dic)
# urls.py
url(r‘^books/(\d+)‘, views.BookView.as_view())
url(r‘^books/‘, views.BooksView.as_view())
from rest_framework.generics import GenericAPIView
# views.py
class BooksView(GenericAPIView):
queryset = models.Book.objects
serializer_class = BookModelSerializer
def get(self, request):
book_list = self.get_queryset()
book_ser = self.get_serializer(book_list, many=True)
return Response(book_ser.data)
def post(self, request):
book_ser = self.get_serializer(data=request.data)
if book_ser.is_vaild():
book_ser.save()
return Response(book_ser.data)
else:
return Response(book_ser.data)
class BookView(GenericAPIView):
queryset = models.Book.objects
serializer_class = BookModelSerializer
def get(self,request, pk):
book = self.get_object()
book_ser = self.get_serializer(book)
return Response(book_ser.data)
def put(self, request, pk):
book = self.get_object()
book_ser = self.get_serializer(insatnce=book, data=request.data)
if book_ser.is_vaild():
book_ser.save()
return Response(book_ser.data)
else:
return Response({‘status‘:101, ‘msg‘:‘校验失败‘})
def delete(self,request, pk):
ret = self.get_object().delete()
return Response({‘status‘:100, ‘msg‘:‘删除成功‘})
# urls.py
url(r‘^books/(?P<pk>\d+)‘, views.BookView.as_view()),
url(r‘^books/‘, views.BooksView.as_view()),
from rest_framework.mixins import ListModelMixin, CreateModelMixin, DestroyModelMixin, RetrieveModelMixin,UpdateModelMixin
class BookView(ListModelMixin, CreateModelMixin, GenericAPIView):
queryset=models.Book.objects
serializer_class = BookModelSerializer
def get(self, request):
return self.list(request)
def post(self, request):
return self.create(request)
class BooksView(UpdateModelMixin, DestroyModelMixin, RetrieveModelMixin, GenericAPIView):
queryset = models.Book.objects
serializer_class = BookModelSerializer
def get(self,request, pk):
return self.retrieve(request, pk)
def patch(self, request, pk):
return self.update(request, pk)
def delete(self,request, pk):
return self.destroy(request, pk)
# views.py
from rest_framework.viewsets import ModelViewSet
# 四行代码搞定5个接口
class BookView(ModelViewSet):
queryset = model.Book.objects
serializer_class = BookSerializer
# urls.py
# 使用ModelViewSet编写5个接口
url(r‘^books/(?P<pk>\d+)‘, views.BookView.as_view(actions={‘get‘:‘retrieve‘, ‘put‘:‘update‘,‘delete‘:‘destroy‘})),
url(r‘^books/‘, views.BooksView.as_view(actions={‘get‘:‘list‘, ‘post‘:‘create‘})),
# 路径匹配时,如果是get请求,会执行list方法
# 重写了as_view
for method, action in actions.items():
handler = getattr(self, action) # 使用反射,handler就是对应函数方法的内存地址
setattr(self, method, handler) # 反射,设置属性对应handler
from rest_framework.viewsets import ViewSetMixin
class BookBiew(ViewSetMixin, APIView):
def get_all_book(self, request):
print(‘xxx‘)
book_list = models.Book.objects.all()
book_ser = BookSerializer(book_list, many=True)
return Response(book_ser.data)
# urls.py
# 继承ViewSetMixin的视图类,路由可以改写
url(r‘^books/‘,views.BookView.as_view(actions={‘get‘:‘get_all_book‘}))
标签:def res params mode generics 地址 set request xxx
原文地址:https://www.cnblogs.com/liqianxin/p/13269940.html