一、解析器
原生Django支持urlencoded数据的解析,但不支持对json数据的解析,而rest-framework支持这两种数据的解析
局部视图
#没有配置的情况默认JSONParser,FormParser,MultiPartParser,最常用的也是前两种 from rest_framework.parsers import JSONParser,FormParser class PublishViewSet(generics.ListCreateAPIView): parser_classes = [FormParser,JSONParser] #这里不配置parser_classes会去父类(APIV类)找默认的 parser_classes queryset = Publish.objects.all()# serializer_class = PublshSerializers# def post(self, request, *args, **kwargs):# print("request.data",request.data) return self.create(request, *args, **kwargs)
全局视图
REST_FRAMEWORK={ "DEFAULT_AUTHENTICATION_CLASSES":["app01.service.auth.Authentication",], "DEFAULT_PERMISSION_CLASSES":["app01.service.permissions.SVIPPermission",], "DEFAULT_THROTTLE_CLASSES":["app01.service.throttles.VisitThrottle",], "DEFAULT_THROTTLE_RATES":{ "visit_rate":"5/m", }, "DEFAULT_PARSER_CLASSES":['rest_framework.parsers.FormParser',] }
二、路由控制
之前我们对视图类进行了封装:
class AuthorModelView(viewsets.ModelViewSet): queryset = Author.objects.all() serializer_class = AuthorModelSerializers
但在写url的时候需要写两个
url(r'^authors/$', views.AuthorModelView.as_view({"get":"list","post":"create"}),name="author"), url(r'^authors/(?P<pk>d+)/$', views.AuthorModelView.as_view({"get":"retrieve","put":"update","delete":"destroy"}),name="detailauthor"),
现在对url进行封装:
from django.conf.urls import url,includefrom rest_framework import routers from app01 import views routers=routers.DefaultRouter() #实例化 routers.register("authors",views.AuthorModelView)#注册
#routers.register("books",views.BookModelView) #以后我们添加其它视图的url时只需在这里注册,大大减少了代码量 urlpatterns = [ url(r'', include(routers.urls)), #这一条url实际上会生成4条url ]
三、分页
对于没有封装的视图进行分页:
from rest_framework.pagination import PageNumberPagination,LimitOffsetPagination #自定义分页配置 # 分页器1:比较常用 class MyPageNumberPagination(PageNumberPagination): page_size = 1 #每一页显示多少条数据 page_query_param = 'page' #url中指定显示哪一页的数据 ?page=2 page_size_query_param="size" #临时控制每页显示几条数据 ?page=2&size=2 max_page_size=2 #每页最多显示多少条数据,针对上面的size # 分页器2:可进行偏移设置 class MyLimitOffsetPagination(LimitOffsetPagination): default_limit=1 #默认每页显示一条数据 class BookView(APIView): def get(self,request): book_list=Book.objects.all() #拿到所有数据 # 分页 # pnp = MyPageNumberPagination() #实例化得到分页器对象 pnp=MyLimitOffsetPagination() books_page=pnp.paginate_queryset(book_list,request,self) #分页 bs=BookModelSerializers(books_page,many=True,context={'request': request}) #交给序列化组件 return Response(bs.data)
对于封装好的视图进行分页:
# class AuthorModelView(viewsets.ModelViewSet):# queryset = Author.objects.all() serializer_class = AuthorModelSerializers #分页:只需用pagination_class指定好使用哪个分页器 pagination_class = MyPageNumberPagination #查看源码可知只需这样设置就能实现分页
可以在全局指定每页显示几条数据:
settings.py
REST_FRAMEWORK = { # "DEFAULT_AUTHENTICATION_CLASSES": ["app01.utils.TokenAuth",], # "DEFAULT_PERMISSION_CLASSES": ["app01.utils.SVIPPermission",], "PAGE_SIZE":1 }
四、响应器
为我们配置了一个浏览器的格式
from .models import User from rest_framework.response import Response class LoginView(APIView): authentication_classes = [] def post(self,request): name=request.data.get("name") pwd=request.data.get("pwd") user=User.objects.filter(name=name,pwd=pwd).first() res = {"state_code": 1000, "msg": None} if user: random_str=get_random_str(user.name) token=Token.objects.update_or_create(user=user,defaults={"token":random_str}) res["token"]=random_str else: res["state_code"]=1001 #错误状态码 res["msg"] = "用户名或者密码错误" import json return Response(json.dumps(res,ensure_ascii=False))