django中请求处理方式有2种:FBV(function base views) 和 CBV(class base views),换言之就是一种用函数处理请求,一种用类处理请求。

FBV

# url.py
from django.conf.urls import url, include
from mytest import views urlpatterns = [
url(r‘^index/‘, views.index),
] # views.py
from django.shortcuts import render def index(req):
if req.method == ‘POST‘:
print(‘method is :‘ + req.method)
elif req.method == ‘GET‘:
print(‘method is :‘ + req.method)
return render(req, ‘index.html‘)

CBV

# urls.py
from mytest import views urlpatterns = [
# url(r‘^index/‘, views.index),
url(r‘^index/‘, views.Index.as_view()),
] # views.py
from django.views import View class Index(View):
def get(self, req):
print(‘method is :‘ + req.method)
return render(req, ‘index.html‘) def post(self, req):
print(‘method is :‘ + req.method)
return render(req, ‘index.html‘) # 注:类要继承 View ,类中函数名必须小写。
# cbv 模式下继承了django的view类
# 在请求来临的时候,会调用继承类的 dispatch 方法
# 通过反射的方法它会去调用自己写的视图函数, 那么这便是一个切入点,可以在自己的 cbv 视图中,重写这个方法。
class View(object): def dispatch(self, request, *args, **kwargs):
# Try to dispatch to the right method; if a method doesn't exist,
# defer to the error handler. Also defer to the error handler if the
# request method isn't on the approved list.
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
return handler(request, *args, **kwargs)

CBV模式下的一个拓展

最新文章

  1. NavisWorks Api 简单使用与Gantt
  2. Atom
  3. [CareerCup] 17.10 Encode XML 编码XML
  4. JQuery text()、html() 以及 val()
  5. C# Server.MapPath()
  6. Python内置数据类型之List篇
  7. 现代C++作业2 与 围棋homework-06
  8. mysql---多表关联
  9. sql 去除结尾的回车或者换行
  10. FZU 1896 神奇的魔法数 dp
  11. 可以有效防护XSS,sql注射,代码执行,文件包含等多种高危漏洞。
  12. Bootstrap+PHP表单验证实例
  13. An SPI class of type org.apache.lucene.codecs.PostingsFormat with name 'Lucene50' does not exist. You need to add the corresponding JAR file supporting this SPI to your classpath. The current classp
  14. dojo:如何显示ListBox风格的选择框
  15. ML平台_Angel参考
  16. 1057 Stack 树状数组
  17. WPF 中textBox实现只输入数字
  18. 2018.09.16 loj#10242. 取石子游戏 2(博弈论)
  19. 裸眼 3D 技术是什么原理?
  20. xml-apis-ext.jar

热门文章

  1. GO语言学习笔记1-输入带空格的字符串
  2. 新建com组件项目步骤
  3. antd不可选择时间
  4. Python抽象类(abc模块)
  5. 同一个tomcat部署多个项目
  6. Java中的可变参数
  7. [LeetCode]-algorithms-Longest Palindromic Substring
  8. linux inotify 监控文件系统事件
  9. 将Windows下的文件同步到Linux下
  10. 一、基础篇--1.1Java基础-抽象类和接口的区别