Python之Django rest_Framework(3)
2018-06-18 01:16:07来源:未知 阅读 ()
补充:
为什么要前后端分离:
a、因为前端它有自己框架,这样它的效率就非常高
b、不做前后端分离,公司如果既有客户端,又有app这种情况下你就的写两遍
django restful框架好处:
帮助我们写了好多组件比如:
a、认证:有类,类中的方法authenticate/authenticate_header,它的返回值有None,元组,异常。如果返回值为None那就不管,它是匿名用户。
b、权限:有类,类中的方法:has_permission
c、节流:有类,类的方法:allow_request,在这里allow_request来表示限制,它是通过IP来限制,
它的内部原理是:默认是IP,用户来用IP,这个IP可能代理IP,IP或者是代理IP拿着请求头默认放到大家能够的缓存中 去,每一个人的IP为p,后面的那个列表存它的方位时间,每一次请求进来获取它的当前时间根据时间的个数来比较,在 比较的过程中看看把不符合时间的个数来进行比较,能访问就继续,不能访问就不要继续。
d、版本:是url和hostname,他们两个钟每一个都有两个方法一个是帮你拿版本另一个是帮你反向生成url
e、解析器:用户发过来的请求体数据进行操作
f、序列化:两个功能:序列化,校验
一、分页
分页的三种情况:
a、记录当前访问页的数据id
b、最多显示120页
c、对页码进行加密
a、基于limit offset做分页
class P1(LimitOffsetPagination):
max_limit = 3
default_limit = 2
limit_query_param = 'limit'
offset_query_param = 'offset'
class IndexView(views.APIView):
def get(self,request,*args,**kwargs):
user_list = models.UserInfo.objects.all()
p1 = P1()
page_user_list = p1.paginate_queryset(queryset=user_list, request=request, view=self)
ser = IndexSerializer(instance=page_user_list, many=True)
return Response(ser.data) # 不含上一页和下一页
# return p1.get_paginated_response(ser.data) # 含上一页和下一页
class IndexView(views.APIView):
def get(self,request,*args,**kwargs):
ret = BaseResponse()
try:
user_list = models.UserInfo.objects.all()
p1 = P1()
page_user_list = p1.paginate_queryset(queryset=user_list,request=request,view=self)
ser = IndexSerializer(instance=page_user_list,many=True)
ret.data = ser.data
ret.next = p1.get_next_link()
except Exception as e:
ret.code= 1001
ret.error = 'xxxx错误'
return Response(ret.__dict__)
b. 基于页码的分页
class P2(PageNumberPagination): # 每页显示的数据条数 max_page_size = 5 page_size = 2 page_size_query_param = 'size' # 页码 page_query_param = 'page'
c. 基于Cursor的分页
class P3(CursorPagination): cursor_query_param = 'cursor' page_size = 2 ordering = 'id'
from django.conf.urls import url,include from django.contrib import admin urlpatterns = [ #url(r'^admin/', admin.site.urls), url(r'^api/(?P<version>[v1|v2]+)/', include('api.urls')), ]
REST_FRAMEWORK = { "DEFAULT_VERSIONING_CLASS":"rest_framework.versioning.URLPathVersioning", "VERSION_PARAM":'version', "ALLOWED_VERSIONS":['v1','v2'], 'DEFAULT_VERSION':'v1', 'PAGE_SIZE':2 }
from django.shortcuts import render from rest_framework import views from rest_framework.response import Response from rest_framework.pagination import LimitOffsetPagination from api import models from api.serializers.index import IndexSerializer class BaseResponse(object): def __init__(self,code=1000,data=None,error=None): self.code = code self.data = data self.error = error class P1(LimitOffsetPagination): max_limit = 3 default_limit = 2 limit_query_param = 'limit' offset_query_param = 'offset' class IndexView(views.APIView): def get(self, request, *args, **kwargs): ret = BaseResponse() try: user_list = models.UserInfo.objects.all() p1 = P1() page_user_list = p1.paginate_queryset(queryset=user_list,request=request,view=self) ser = IndexSerializer(instance=page_user_list,many=True) ret.data = ser.data ret.next = p1.get_next_link() except Exception as e: ret.code= 1001 ret.error = 'xxxx错误' return Response(ret.__dict__)
from django.conf.urls import url,include from django.contrib import admin from api import views urlpatterns = [ url(r'^index/$', views.IndexView.as_view()), ]
二、视图
1、APIView
class IndexView(views.APIView):
def get(self, request, *args, **kwargs):
user_list = models.UserInfo.objects.all()
ser = IndexSerializer(instance=user_list,many=True)
return Response(ser.data)
2、GenericAPIview(APIView)
3、GenericViewSet(ViewSetMixin,generics.GenericAPIView)
路由修改:
urlpatterns = [
url(r'^index/$', views.IndexView.as_view({'get':'list','post':'create'})),
url(r'^index/(?P<pk>\d+)$', views.IndexView.as_view({'get':'retrieve'})),
]
视图修改:
class IndexView(viewsets.GenericViewSet):
def list(self,request,*args,**kwargs):
pass # 获取列表信息
def retrieve(self, request, *args, **kwargs):
pass # 获取单条数据
def create(self,request, *args, **kwargs):
pass
自定义:
增
POST
/users/
删
DELETE
/users/1/
改
PUT
/users/1/
patch
/users/1/
查
GET
/users/
GET
/users/1/
urlpatterns = [
url(r'^index/$', views.IndexView.as_view()),
url(r'^index/(?P<pk>\d+)$', views.IndexView.as_view()),
]
class IndexView(views.APIView):
def get(self,request,*args,**kwargs):
pk = kwargs.get('pk')
if pk:
pass # 获取单条信息
else:
pass # 获取列表信息
def post(self,request,*args,**kwargs):
pass
def put(self,request,*args,**kwargs):
pass
def patch(self,request,*args,**kwargs):
pass
def delete(self,request,*args,**kwargs):
pass
4、ModelViewSet
ModelViewSet(mixins.CreateModelMixin,mixins.RetrieveModelMixin,mixins.UpdateModelMixin,mixins.DestroyModelMixin,mixins.ListModelMixin,GenericViewSet)
class IndexView(ModelViewSet):
REST_FRAMEWORK = { "DEFAULT_VERSIONING_CLASS":"rest_framework.versioning.URLPathVersioning", "VERSION_PARAM":'version', "ALLOWED_VERSIONS":['v1','v2'], 'DEFAULT_VERSION':'v1', # 'PAGE_SIZE':2 }
from django.conf.urls import url,include from django.contrib import admin urlpatterns = [ #url(r'^admin/', admin.site.urls), url(r'^api/(?P<version>[v1|v2]+)/', include('api.urls')), ]
from django.shortcuts import render from rest_framework import views from rest_framework import generics from rest_framework import viewsets from rest_framework.response import Response from rest_framework.pagination import LimitOffsetPagination,PageNumberPagination,CursorPagination from api import models from api.serializers.index import IndexSerializer class P2(PageNumberPagination): # 每页显示的数据条数 max_page_size = 5 page_size = 2 page_size_query_param = 'size' # 页码 page_query_param = 'page' class IndexView(viewsets.ModelViewSet): queryset = models.UserInfo.objects.all() serializer_class = IndexSerializer pagination_class = P2
from django.conf.urls import url,include from django.contrib import admin from api import views urlpatterns = [ url(r'^index/$', views.IndexView.as_view({'get':'list','post':'create'})), url(r'^index/(?P<pk>\d+)/$', views.IndexView.as_view({'get':'retrieve','delete':'destroy','put':'update','patch':'partial_update'})), ]
3. 路由
第一类:
# http://127.0.0.1:8000/api/v1/auth/ url(r'^auth/$', views.AuthView.as_view()), # http://127.0.0.1:8000/api/v1/auth.json # 想要让页面显示json格式 url(r'^auth\.(?P<format>[a-z0-9]+)$', views.AuthView.as_view()), # http://127.0.0.1:8000/api/v1/auth/1/ url(r'^auth/(?P<pk>\d+)/$', views.AuthView.as_view()), # http://127.0.0.1:8000/api/v1/auth/1.json url(r'^auth/(?P<pk>\d+)\.(?P<format>[a-z0-9]+)$', views.AuthView.as_view()), class AuthView(views.APIView): def get(self,request,*args,**kwargs): return Response('...')
第二类:
url(r'^index/$', views.IndexView.as_view({'get':'list','post':'create'})), url(r'^index/\.(?P<format>[a-z0-9]+)$', views.IndexView.as_view({'get':'list','post':'create'})), url(r'^index/(?P<pk>\d+)/$', views.IndexView.as_view({'get':'retrieve','delete':'destroy','put':'update','patch':'partial_update'})), url(r'^index/(?P<pk>\d+)\.(?P<format>[a-z0-9]+)$', views.IndexView.as_view({'get':'retrieve','delete':'destroy','put':'update','patch':'partial_update'})), class IndexView(viewsets.ModelViewSet): queryset = models.UserInfo.objects.all() serializer_class = IndexSerializer pagination_class = P2
第三类:
router = DefaultRouter() router.register('index',views.IndexViewSet) urlpatterns = [ url(r'^', include(router.urls)), ] class IndexViewSet(viewsets.ModelViewSet): queryset = models.UserInfo.objects.all() serializer_class = IndexSerializer pagination_class = P2 class IndexSerializer(serializers.ModelSerializer): class Meta: model = models.UserInfo fields = "__all__"
4. 渲染器
看到的页面时什么样子的,返回数据。
renderer_classes = [JSONRenderer,BrowsableAPIRenderer]
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
上一篇:python:线程进阶
- python3基础之“术语表(2)” 2019-08-13
- python3 之 字符串编码小结(Unicode、utf-8、gbk、gb2312等 2019-08-13
- Python3安装impala 2019-08-13
- 小白如何入门 Python 爬虫? 2019-08-13
- python_字符串方法 2019-08-13
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash