Rest_framework-3
目录:
一 返回值的封装
a. API的基本框架
setting:
1 首先注册rest_framework 2 版本配置 REST_FRAMEWORK = {
"DEFAULT_VERSIONING_CLASS":"rest_framework.versioning.URLPathVersioning",
"VERSION_PARAM":"version",
"ALLOWED_VERSIONS":['v1','v2'],
"DEFAULT_VERSION":"v1",
}
urls.py:
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')),
] # 路由分发
api路径:
from django.conf.urls import url,include
from django.contrib import admin
from api import views urlpatterns = [
url(r'^index/$',views.IndexView.as_view()),
]
views:
from rest_framework import views
from rest_framework.response import Response class IndexView(views.APIView):
def get(self,request,*args,**kwargs): return Response('...')
b.返回值封装的方法:
# 配置、路径与上相同
views视图:
from rest_framework import views
from rest_framework.response import Response 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 IndexView(views.APIView):
def get(self,request,*args,**kwargs):
ret = BaseResponse()
try:
user_list = models.UserInfo.objects.all()
ser = IndexSerializer(instance=user_list,many=True) ret.data = ser.data
except Exception as e:
ret.code = 1001
ret.error = 'xxx错误'
return Response(ret.__dict__)
对象方法
from rest_framework import views
from rest_framework.response import Response from api import models
from api.serializers.index import IndexSerializer class IndexView(views.APIView):
def get(self,request,*args,**kwargs):
ret = {'code': 1000,'data':None }
try:
user_list = models.UserInfo.objects.all()
ser = IndexSerializer(instance=user_list,many=True) ret['data'] = ser.data
except Exception as e:
ret['code'] = 1001
ret['error'] = 'xxx错误'
return Response(ret)
字典方法
# 创建serlalizers文件 存放序列化类的py文件
from rest_framework import serializers class IndexSerializer(serializers.Serializer):
id = serializers.IntegerField()
name = serializers.CharField()
pwd = serializers.CharField()
index
二 分页
分页最常见的三种情况:
1. 记录当前访问页的数据id 2. 最多显示120页 3. 对页码进行加密
a.基于limit offset做分页
自定义分页:
from rest_framework.pagination import LimitOffsetPagination 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) # 含上一页和下一页
添加分页功能:
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):
default_limit = 2 # 默认显示数据条数
limit_query_param = 'limit'
offset_query_param = 'offset'
max_limit = 3 # 限制最大显示条数 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.基于页码的分页
from rest_framework.pagination import PageNumberPagination class P2(PageNumberPagination):
# 每页显示的数据条数
max_page_size = 5
page_size = 2
page_size_query_param = 'size' # 页码
page_query_param = 'page'
c.基于Cursor的分页(解决大数据分页的问题:页码加密)
from rest_framework.pagination import CursorPagination class P3(CursorPagination):
cursor_query_param = 'cursor'
page_size = 2
ordering = 'id'
ps:源码中不同的分页功能封装在不同的模块里,使用时可以根据需要将模块里的方法自定义,也可以配置在全局
三 视图
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
4. ModelViewSet(mixins.CreateModelMixin,mixins.RetrieveModelMixin,mixins.UpdateModelMixin,mixins.DestroyModelMixin,mixins.ListModelMixin,GenericViewSet) 自定义类:
class IndexView(ModelViewSet):
自定义:
增
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
ps:工作中最常用第1种(完全自定义)和第4种(封装最多,需要那种方法就引用那种模块),第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
第三类:(自动生成)
from rest_framework.routers import DefaultRouter
from rest_framework import views 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__"
五 渲染器
看到的页面是什么样子的,返回数据。
urls.py:
urlpatterns = [
url(r'^index/$', views.IndexView.as_view()),
url(r'^index\.(?P<format>[a-z0-9]+)$', views.IndexView.as_view()),
]
views.py
class IndexView(views.APIView): renderer_classes = [JSONRenderer,BrowsableAPIRenderer] def get(self,request,*args,**kwargs):
self.dispatch
user_list = models.UserInfo.objects.all()
ser = IndexSerializer(instance=user_list,many=True)
return Response(ser.data)
ps:通过路径后缀来决定返回页面的格式,默认是JSONRenderer模块,返回json字符串,
Rest_framework-3的更多相关文章
- Django rest_framework 实用技巧
前言: 最近工作中需要用到Django rest_framework框架做API, 边学边写,记录了一些实际工作中需要用到的功能,不是很全也不系统,以后需要什么功能可以在这查询. 后续还会更新其它的用 ...
- django rest_framework--入门教程3
rest_framwork 之post 与put rest_framwork可以接受post与put delete get请求,可以对资源进行刚CRUD,以一个DEMO为例, 1.先在VIEW里定义一 ...
- django rest_framework--入门教程2
接上文 这里先写一个GET请求的 1.先在VIEW里定义一个方法 代码如下: @api_view(['GET', 'POST']) def book_request(request): if requ ...
- django rest_framework
环境 django 1.6,rest_framework 3.3 ubuntu采用pip安装的rest_framework 按照例子一步步做下来 运行 提示filters.py第119行有错误form ...
- REST_FRAMEWORK加深记忆-极致抽象,极致完结
余下的就是静心看官方文档了. 这个是最抽象的了. urls.py """tutorial URL Configuration The `urlpatterns` list ...
- REST_FRAMEWORK加深记忆-加了API_ROOT及超链接的CASE
urls.py from django.conf.urls import url from rest_framework.urlpatterns import format_suffix_patter ...
- REST_FRAMEWORK加深记忆-加了用户登陆认证,自定义权限的API接口
哈哈,终于快结束了.. urls.py from django.conf.urls import include, url from django.contrib import admin urlpa ...
- REST_FRAMEWORK加深记忆-三种CLASS VIEW的进化史
一层一层的封装,又能到底层,就会有全局感啦... from rest_framework import status from rest_framework.response import Respo ...
- REST_FRAMEWORK加深记忆-第二次练习官方文档2
优化前和优化后的代码,融在一起,能看看进化的过程. MODELS.PY from django.db import models from pygments.lexers import get_all ...
- REST_FRAMEWORK加深记忆-第二次练习官方文档
我想,其它几个基于PYTHON的REST API模块概念都差不多吧. 先深入搞定这个吧. 前几次练习完了有一些印象,并且在工作中实践过一个,现在多弄几次,玩熟悉点. Serializers.py __ ...
随机推荐
- PHP——文本编辑器
简单的代码演示 详细文件在文件目录里 <!doctype html> <html> <head> <meta charset="utf-8" ...
- linux重命名session和window
重命名 window title 最近想要给screen session中的每一个 窗口命名一个标识名字,而不是默认的 $ bash 相关命令: ctrl+z(我的screen配置的+z,默认是+a) ...
- linux命名对文件的读写和退出
vi xxx.txt 打开就能看到里面的内容.按 i 进入编辑模式,然后就可以输入内容了,也可以移动光标到你要删除内容的位置按删除键来删除内容.编辑完后可以按 Esc(键盘左上角) 进入命令模式.然后 ...
- 拖拽 支持ie6
可随意拖拽方块至任一位置: 1.setCapture方法:多用于容器对象,效果是对指定的对象设置鼠标捕获.使在容器内的子对象的鼠标事件均由容器对象触发,因此,只能在容器对象的鼠标事件函数中进行处理.当 ...
- java 教程
1.视频教程 http://blog.csdn.net/zhangdaiscott/article/details/18220411 2.书籍教程: 3.学习课程
- 什么是 end-to-end 神经网络?——知乎解答
什么是 end-to-end 神经网络? https://www.zhihu.com/question/51435499 解答1 张旭 像机器一样学习,像人一样生活 YJango 等 端到端指的是 ...
- EJB包含哪3种bean
EJB包含哪3种bean 解答:session bean(会话bean), entity bean(实体bean), message bean(消息bean)
- (转)java中Executor、ExecutorService、ThreadPoolExecutor介绍
转自: http://blog.csdn.net/linghu_java/article/details/17123057 ScheduledThreadPoolExecutor介绍: http:// ...
- Linux shell 1-初步认识
1.什么是linux linux是一种操作系统,它可划分为以下四部分 1.linux内核(Linux系统的核心,负责管理系统内存,硬件驱动,文件系统等) 2.GNU工具(一组软件工具,提供一些类UNI ...
- 【BZOJ3207】花神的嘲讽计划Ⅰ Hash+主席树
[BZOJ3207]花神的嘲讽计划Ⅰ Description 背景 花神是神,一大癖好就是嘲讽大J,举例如下: “哎你傻不傻的![hqz:大笨J]” “这道题又被J屎过了!!” “J这程序怎么跑这么快 ...