CBV与FBV

restful协议

     ----  一切皆是资源,操作只是请求方式

     ----book表增删改查
/books/ books
/books/add/ addbook
/books/(\d+)/change/ changebook
/books/(\d+)/delete/ delbook ----book表增删改查
/books/ -----get books ----- 返回当前所有数据
/books/ -----post books ----- 返回提交数据 /books/(\d+)-----get bookdetail ----- 返回当前查看的单条数据
/books/(\d+)-----put bookdetail ----- 返回更新数据
/books/(\d+)-----delete bookdetail ----- 返回空 class Books(View):
def get(self,request):
pass # 查看所有书籍 def post(self,request):
pass # 添加书籍 class BooksDetail(View):
def get(self,request,id):
pass # 查看具体书籍 def put(self,request,id):
pass # 更新某本书籍 def delete(self,request,id):
pass # 删除某本书籍 restframework(Django) ----针对数据:json ()Django的原生request: 浏览器 ------------- 服务器 "GET url?a=1&b=2 http/1.1\r\user_agent:Google\r\ncontentType:urlencoded\r\n\r\n"
"POST url http/1.1\r\user_agent:Google\r\ncontentType:urlencoded\r\n\r\na=1&b=2" request.body: a=&b=
request.POST:
if contentType:urlencoded:
a=&b=----->{"a":,"b":} ()restframework 下的APIView: ()
class PublishSerializers(serializers.Serializer):
name=serializers.CharField()
email=serializers.CharField() PublishSerializers(queryset,many=true)
PublishSerializers(model_obj) 总结:
reuqest类----源码 restframework 下的APIView--源码 url(r'^books/$', views.BookView.as_view(),name="books")# View下的view books/一旦被访问: view(request) ------APIView: dispatch() def dispatch(): 构建request对象
self.request=Request(request)
self.request._request
self.request.GET # get
self.request.data # POST PUT 分发----if get请求:
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(),
self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed response = handler(request, *args, **kwargs) # self.get(request, *args, **kwargs) return response 序列化类
# from django.core import serializers
# ret=serializers.serialize("json",publish_list) restframework下的序列类 BookModelSerializers
将queryset或者model对象序列成一json数据
bs=BookModelSerializers(book_list,many=True,context={'request': request})
bs=BookModelSerializers(book,context={'request': request}) 还可以做校验数据,json-------》queryset/model-->记录 bs=BookModelSerializers(data=request.data)
if bs.is_valid():
print(bs.validated_data)
bs.save() # 重写create方法
操作数据: 以Book表为例
class BookView(APIView):
# 查看所有书籍
def get(self,request):
book_list=Book.objects.all()
bs=BookModelSerializers(book_list,many=True,context={'request': request})
return Response(bs.data) # 添加一本书籍
def post(self,request):
# post请求的数据
bs=BookModelSerializers(data=request.data)
if bs.is_valid():
print(bs.validated_data)
bs.save()# create方法
return Response(bs.data)
else:
return Response(bs.errors) class BookDetailView(APIView):
# 查看一本书籍
def get(self,request,id): book=Book.objects.filter(pk=id).first()
bs=BookModelSerializers(book,context={'request': request})
return Response(bs.data)
# 更新一本书籍
def put(self,request,id):
book=Book.objects.filter(pk=id).first()
bs=BookModelSerializers(book,data=request.data)
if bs.is_valid():
bs.save()
return Response(bs.data)
else:
return Response(bs.errors)
# 删除某一本书籍
def delete(self,request,id):
Book.objects.filter(pk=id).delete() return Response()
 CBV

 APIView
class BookView(APIView):pass
url(r'^books/$', views.BookView.as_view(),name="books"),
url(r'^books/$', View类下的view,name="books"),
一旦访问books/: view(request)======APIView类下的dispatch()====请求方式对应的示例方法() def dispatch():
#一 初始化操作
# () 构建新的request:
self.request=self.initial_request()
# self.request._request
# self.request.GET
# self.request.data
# () 执行组件
# 认证,权限,频率
# 认证:request.user
self.initial(request, *args, **kwargs)
==== # 认证组件
self.perform_authentication(request)
==== request.user
=====
for authenticator in self.authenticators: # [TokenAuth(),]
try:
user_auth_tuple = authenticator.authenticate(self)
except exceptions.APIException:
self._not_authenticated()
raise if user_auth_tuple is not None:
self._authenticator = authenticator
self.user, self.auth = user_auth_tuple
return # 权限组件
self.check_permissions(request)
===========
for permission in self.get_permissions():
if not permission.has_permission(request, self):
self.permission_denied(
request, message=getattr(permission, 'message', None)
) # 频率组件
self.check_throttles(request) =============
for throttle in self.get_throttles(): # [VisitRateThrottle(),]
if not throttle.allow_request(request, self):
self.throttled(request, throttle.wait()) # 受限制 # 分发
if request.method.lower() in self.http_method_names:
handler = getattr(self,request.method.lower(),
self.http_method_not_allowed) response = handler(request, *args, **kwargs) return response 序列化组件 class PublishSerializers(serializers.Serializer):
name = serializers.CharField()
email = serializers.CharField() class PublishModelSerializers(serializers.ModelSerializer):
class Meta:
model=Publish
fields="__all__" # queryset或者model对象-------------》json数据
ps=PublishSerializers(queryset,many=True)
ps.data # [{},{},{}] ps=PublishSerializers(model_obj,many=False)
ps.data # {} # json数据-------》记录
# 添加操作
ps=PublishSerializers(data=request.data)
if ps.is_valid():
ps.save() # create # 更新操作 ps=PublishSerializers(model_obj,data=request.data)
if ps.is_valid():
ps.save() # update 视图组件
# 版本1:
# Book表
class BookView(APIView): def get(self,request):
book_list=Book.objects.all()
bs=BookModelSerializers(book_list,many=True,context={'request': request})
return Response(bs.data)
def post(self,request):
# post请求的数据
bs=BookModelSerializers(data=request.data)
if bs.is_valid():
print(bs.validated_data)
bs.save()# create方法
return Response(bs.data)
else:
return Response(bs.errors) class BookDetailView(APIView): def get(self,request,id): book=Book.objects.filter(pk=id).first()
bs=BookModelSerializers(book,context={'request': request})
return Response(bs.data) def put(self,request,id):
book=Book.objects.filter(pk=id).first()
bs=BookModelSerializers(book,data=request.data)
if bs.is_valid():
bs.save()
return Response(bs.data)
else:
return Response(bs.errors) def delete(self,request,id):
Book.objects.filter(pk=id).delete() return Response() # 版本2:mixIn from rest_framework import mixins
from rest_framework import generics class AuthorView(mixins.ListModelMixin,mixins.CreateModelMixin,generics.GenericAPIView):
queryset=Author.objects.all()
serializer_class =AuthorModelSerializers def get(self,request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self,request, *args, **kwargs):
return self.create(request, *args, **kwargs) class AuthorDetailView(mixins.RetrieveModelMixin,mixins.DestroyModelMixin,mixins.UpdateModelMixin,generics.GenericAPIView):
queryset = Author.objects.all()
serializer_class = AuthorModelSerializers def get(self,request,*args, **kwargs):
return self.retrieve(request,*args, **kwargs) def delete(self,request,*args, **kwargs):
return self.destroy(request,*args, **kwargs) def put(self,request,*args, **kwargs):
return self.retrieve(request,*args, **kwargs) # 版本3:基于通用类
from rest_framework import mixins
from rest_framework import generics class AuthorView(generics.ListCreateAPIView):
queryset=Author.objects.all()
serializer_class =AuthorModelSerializers class AuthorDetailView(generics.RetrieveUpdateDestroyAPIView):
queryset = Author.objects.all()
serializer_class = AuthorModelSerializers # 版本4
class AuthorModelView(viewsets.ModelViewSet):
queryset = Author.objects.all()
serializer_class = AuthorModelSerializers 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" 流程:
url(r'^authors/$', views.AuthorModelView.as_view({"get":"list","post":"create"}),name="author"),
url(r'^authors/$', ViewSetMixin.as_view({"get":"list","post":"create"}),name="author"),
url(r'^authors/$', ViewSetMixin类下的view),
一旦访问 /authors/:
ViewSetMixin
def view():
for method, action in actions.items(): # {"get":"list","post":"create"}
handler = getattr(self, action) # self.list self.create
setattr(self, method, handler) self.dispatch(request, *args, **kwargs) APIView类下的self.dispatch
# 分发
if request.method.lower() in self.http_method_names:
handler = getattr(self,request.method.lower(),
self.http_method_not_allowed) response = handler(request, *args, **kwargs) # self.list() return response 认证权限频率 组件 request.META:
{'ALLUSERSPROFILE': 'C:\\ProgramData',
'APPDATA': 'C:\\Users\\Administrator\\AppData\\Roaming',
'COMMONPROGRAMFILES': 'C:\\Program Files\\Common Files',
'COMMONPROGRAMFILES(X86)': 'C:\\Program Files (x86)\\Common Files',
'COMMONPROGRAMW6432': 'C:\\Program Files\\Common Files',
'COMPUTERNAME': 'PC201712041709',
'COMSPEC': 'C:\\Windows\\system32\\cmd.exe',
'DJANGO_SETTINGS_MODULE': 'restdemo.settings',
'FP_NO_HOST_CHECK': 'NO', 'HOMEDRIVE': 'C:',
'HOMEPATH': '\\Users\\Administrator',
'LOCALAPPDATA': 'C:\\Users\\Administrator\\AppData\\Local',
'LOGONSERVER': '\\\\PC201712041709',
'NUMBER_OF_PROCESSORS': '', 'OS': 'Windows_NT',
'PATH': 'C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36;C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\Scripts;C:\\Python27;E:\\MySQL Server 5.6\\bin;C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\Scripts\\;C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\;C:\\Users\\Administrator\\AppData\\Local\\atom\\bin',
'PATHEXT': '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC',
'PROCESSOR_ARCHITECTURE': 'AMD64',
'PROCESSOR_IDENTIFIER': 'Intel64 Family 6 Model 60 Stepping 3, GenuineIntel',
'PROCESSOR_LEVEL': '', 'PROCESSOR_REVISION': '3c03',
'PROGRAMDATA': 'C:\\ProgramData',
'PROGRAMFILES': 'C:\\Program Files',
'PROGRAMFILES(X86)': 'C:\\Program Files (x86)',
'PROGRAMW6432': 'C:\\Program Files',
'PSMODULEPATH': 'C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Modules\\',
'PUBLIC': 'C:\\Users\\Public', 'PYCHARM_HOSTED': '', 'PYTHONIOENCODING': 'UTF-8',
'PYTHONPATH': 'C:\\Users\\Administrator\\PycharmProjects\\s9\\restdemo', 'PYTHONUNBUFFERED': '',
'SESSIONNAME': 'Console', 'SYSTEMDRIVE': 'C:', 'SYSTEMROOT': 'C:\\Windows',
'TEMP': 'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp', 'TMP': 'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp',
'USERDOMAIN': 'PC201712041709',
'USERNAME': 'Administrator',
'USERPROFILE': 'C:\\Users\\Administrator',
'WINDIR': 'C:\\Windows', 'WINDOWS_TRACING_FLAGS': '',
'WINDOWS_TRACING_LOGFILE': 'C:\\BVTBin\\Tests\\installpackage\\csilogfile.log',
'RUN_MAIN': 'true', 'SERVER_NAME': 'PC201712041709',
'GATEWAY_INTERFACE': 'CGI/1.1', 'SERVER_PORT': '',
'REMOTE_HOST': '',
'CONTENT_LENGTH': '',
'SCRIPT_NAME': '',
'SERVER_PROTOCOL': 'HTTP/1.1',
'SERVER_SOFTWARE': 'WSGIServer/0.2',
'REQUEST_METHOD': 'GET',
'PATH_INFO': '/authors/',
'QUERY_STRING': 'token=8204b8e3ac40bf59ae480d17c146b51a',
'REMOTE_ADDR': '127.0.0.1',
'CONTENT_TYPE': 'text/plain',
'HTTP_HOST': '127.0.0.1:8000',
'HTTP_CONNECTION': 'keep-alive',
'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
'HTTP_UPGRADE_INSECURE_REQUESTS': '',
'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'HTTP_ACCEPT_ENCODING': 'gzip, deflate, br', 'HTTP_ACCEPT_LANGUAGE': 'zh-CN,zh;q=0.9', 'HTTP_COOKIE': 'csrftoken=jtus3l4GJEc9TFXWYCWxkBIZprcOv7C1vFMIyOHs7Zkxt015FwVZ2KEEeDV6LOyN', 'wsgi.input': <_io.BufferedReader name=>, 'wsgi.errors': <_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>, 'wsgi.version': (, ), 'wsgi.run_once': False, 'wsgi.url_scheme': 'http', 'wsgi.multithread': True, 'wsgi.multiprocess': False, 'wsgi.file_wrapper': <class 'wsgiref.util.FileWrapper'>} 解析器-----数据解析器
from rest_framework.parsers import JSONParser,FormParser,MultiPartParser,FileUploadParser
parser_classes = [JSONParser,FormParser] 路由控制
针对:
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"), class AuthorModelView(viewsets.ModelViewSet): queryset = Author.objects.all()
serializer_class = AuthorModelSerializers url(r'^books/$', views.BookModelView.as_view({"get":"list","post":"create"}),name="author"),
url(r'^books/(?P<pk>\d+)/$', views.BookModelView.as_view({"get":"retrieve","put":"update","delete":"destroy"}),name="detailbook"), class AuthorModelView(viewsets.ModelViewSet): queryset = Author.objects.all()
serializer_class = AuthorModelSerializers 分页 响应器 Response

CBV FBV rest framework的更多相关文章

  1. Python/Django(CBV/FBV/ORM操作)

    Python/Django(CBV/FBV/ORM操作) CBV:url对应的类(模式) ##====================================CBV操作============ ...

  2. Django 的 CBV&FBV

    Django FBV, function base view  视图里使用函数处理请求 url 1 url(r‘^users/‘, views.users), views 1 2 3 4 5 from ...

  3. Django之CBV\FBV

    FBV(function base views) 就是在视图里使用函数处理请求. 写一个FBV的实例:在views中代码 :就是写了个函数 def book(request): ''' :param ...

  4. day054 组件 CBV FBV 装饰器 ORM增删改查

    组件: ​ 把一小段HTML 放在一个HTML中 nav.html ​ 使用: ​ {% include ‘nav.html ’ %} 一. FBV 和CBV 1.FBV(function base ...

  5. 巨蟒python全栈开发django5:组件&&CBV&FBV&&装饰器&&ORM增删改查

    内容回顾: 补充反向解析 Html:{% url ‘别名’ 参数 %} Views:reverse(‘别名’,args=(参数,)) 模板渲染 变量 {{ 变量名 }} 逻辑相关 {% %} 过滤器: ...

  6. Django 之 CBV & FBV

    FBV FBV(function base views) 就是在视图里使用函数处理请求. 在之前django随笔中,一直使用的是这种方式,不再赘述. CBV CBV(class base views) ...

  7. Django之Cookie Session详解,CBV,FBV登陆验证装饰器和自定义分页

    Cookie Session和自定义分页   cookie Cookie的由来 大家都知道HTTP协议是无状态的. 无状态的意思是每次请求都是独立的,它的执行情况和结果与前面的请求和之后的请求都无直接 ...

  8. django的FBV和CBV

    title: python djano CBV FBV tags: python, djano, CBV, FBV grammar_cjkRuby: true --- python django的fu ...

  9. django请求生命周期,FBV和CBV,ORM拾遗,Git

    一.django 请求生命周期 流程图: 1. 当用户在浏览器中输入url时,浏览器会生成请求头和请求体发给服务端请求头和请求体中会包含浏览器的动作(action),这个动作通常为get或者post, ...

随机推荐

  1. Class-reference types 类引用类型--快要失传的技术

    先摘一段原版的说明: A class-reference type, sometimes called a metaclass, is denoted by a construction of the ...

  2. Spring3.0学习1.2(使用annotation)

    使用annotation 首先 xml文件更改  新加xslt <?xml version="1.0" encoding="UTF-8"?> < ...

  3. ArcGIS案例学习笔记4_2_水文分析批处理地理建模

    ArcGIS案例学习笔记4_2_水文分析批处理地理建模 联系方式:谢老师,135_4855_4328,xiexiaokui#139.com 概述 计划时间:第4天下午 目的:自动化,批量化,批处理,提 ...

  4. ztree根据treeId展开指定节点并触发单击事件

    ztree.expandNode(ztree.getNodeByParam("id",treeId,null));//展开指定节点 ztree.selectNode(ztree.g ...

  5. NYOJ44-子串和-(dp||思维)

    题目描述: 给定一整型数列{a1,a2...,an},找出连续非空子串{ax,ax+1,...,ay},使得该子序列的和最大,其中,1<=x<=y<=n. 输入描述: 第一行是一个整 ...

  6. tomcat支持 https

    首先 安装nginx  ,在nginx.conf 中引入 include /app/conf/nginx/vhosts/*.conf; 配置 并在conf/vhosts 目录 中配置virtual.c ...

  7. matlab 画二维图与三维图

    二维图 ezplot('sin(x)');%默认范围 ezplot('sin(x)',[-4 4]);%自己设定范围 三维图 ezmesh('x*x+y*y');%默认范围

  8. 消息队列RabbitMQ与Spring

    1.RabbitMQ简介 RabbitMQ是流行的开源消息队列系统,用erlang语言开发.RabbitMQ是AMQP(高级消息队列协议)的标准实现. 官网:http://www.rabbitmq.c ...

  9. mysql 定时备份任务

    备份方案: 本地备份并同步至远程服务器,保留30天数据 1. 本地数据库备份,备份数据库gold_ecooy,naiang#!/bin/bash#xliang#Created Time: 2018-1 ...

  10. 四、Factory Method 工厂方法模式

    需求:对象的创建由工厂统一创建,会使用到模板模式 代码清单: 工厂: public abstract class Factory { public abstract Product createPro ...