django基类View.as_view()
参考:https://www.zmrenwu.com/post/53/
详细见参考
一般请求的判断方法:
- def view(request, *args, **kwargs):
- if request.method.lower() == 'get':
- do_something()
- if request.method.lower() == 'post':
- do_something()
使用View.as_view()代替判断:
- class ClassName(View):
- '''
- 继承View自动判断请求方法
- '''
- def post():
- pass
- def get():
- pass
- def other():
- pass
- #调用方法
- url(url, ClassName.as_view(), name)
设计思想:把视图函数的逻辑定义到类的方法里面去,然后在函数中实例化这个类,通过调用类的方法实现函数逻辑,而把逻辑定义在类中的一个好处就是可以通过继承复用这些方法。
- class View(object):
- """
- Intentionally simple parent class for all views. Only implements
- dispatch-by-method and simple sanity checking.
- """
- http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
- def __init__(self, **kwargs):
- """
- Constructor. Called in the URLconf; can contain helpful extra
- keyword arguments, and other things.
- """
- # Go through keyword arguments, and either save their values to our
- # instance, or raise an error.
- for key, value in six.iteritems(kwargs):
- setattr(self, key, value)
- @classonlymethod
- def as_view(cls, **initkwargs):
- """
- Main entry point for a request-response process.
- """
- for key in initkwargs:
- if key in cls.http_method_names:
- raise TypeError("You tried to pass in the %s method name as a "
- "keyword argument to %s(). Don't do that."
- % (key, cls.__name__))
- if not hasattr(cls, key):
- raise TypeError("%s() received an invalid keyword %r. as_view "
- "only accepts arguments that are already "
- "attributes of the class." % (cls.__name__, key))
- def view(request, *args, **kwargs):
- self = cls(**initkwargs)
- if hasattr(self, 'get') and not hasattr(self, 'head'):
- self.head = self.get
- self.request = request
- self.args = args
- self.kwargs = kwargs
- return self.dispatch(request, *args, **kwargs)
- view.view_class = cls
- view.view_initkwargs = initkwargs
- # take name and docstring from class
- update_wrapper(view, cls, updated=())
- # and possible attributes set by decorators
- # like csrf_exempt from dispatch
- update_wrapper(view, cls.dispatch, assigned=())
- return view
- 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)
- def http_method_not_allowed(self, request, *args, **kwargs):
- logger.warning(
- 'Method Not Allowed (%s): %s', request.method, request.path,
- extra={'status_code': 405, 'request': request}
- )
- return http.HttpResponseNotAllowed(self._allowed_methods())
- def options(self, request, *args, **kwargs):
- """
- Handles responding to requests for the OPTIONS HTTP verb.
- """
- response = http.HttpResponse()
- response['Allow'] = ', '.join(self._allowed_methods())
- response['Content-Length'] = ''
- return response
- def _allowed_methods(self):
- return [m.upper() for m in self.http_method_names if hasattr(self, m)]
View类源码
django基类View.as_view()的更多相关文章
- 基类View
尽管类视图看上去类的种类繁多,但每个类都是各司其职的,且从类的命名就可以很容易地看出这个类的功能.大致可分为如下三个大的功能块,分别由三个类提供对应的方法: 处理 HTTP 请求.根据 HTTP 请求 ...
- Django——基于类的视图(class-based view)
刚开始的时候,django只有基于函数的视图(Function-based views).为了解决开发视图中繁杂的重复代码,基于函数的通用视图( Funcation-based generic vie ...
- django abstract base class ---- 抽象基类
抽象蕨类用于定义一些同享的列.类本身并不会在数据库端有表与之对应 一.例子: 1.定义一个叫Person 的抽象基类.Student 继承自Person from django.db import m ...
- Django url中可以使用类视图.as_view()进行映射的原因
说明:在练习天天生鲜项目时,对利用类视图去与正则匹配到的url做映射有点疑惑,经过查看他人博客以及自我分析算是整明白了,所以记录一下 参考:https://www.zmrenwu.com/post/5 ...
- django中抽象基类的Foreignkey的定义
class base(models.Model): user = models.ForeignKey(User) class Meta: abstract =True 以上是抽象基类的定义,只有一个公 ...
- django(六):view和cbv
FBV即以函数的形式实现视图函数,CBV即以类的形式实现视图函数:相比而言,CBV根据请求方式书写各自的代码逻辑,结构清晰明了,但是由于多了一层反射机制,性能要差一些:FBV执行效率要高一些,但是代码 ...
- Django——基于类的视图源码分析 二
源码分析 抽象类和常用视图(base.py) 这个文件包含视图的顶级抽象类(View),基于模板的工具类(TemplateResponseMixin),模板视图(TemplateView)和重定向视图 ...
- DRF视图-基类
2个视图基类 REST framework 提供了众多的通用视图基类与扩展类,以简化视图的编写. 为了区分上面请求和响应的代码,我们再次创建一个新的子应用: python manage.py star ...
- Django Function Based View(FBV)和Class Based View (CBV)对比
一.FBV处理过程 首先来看一下FBV逻辑过程: 1.简单过程(借用官方示例): urls: from django.conf.urls import url from . import views ...
随机推荐
- WF控制台工作流(1)
简单使用WF工作流示例: using System; using System.Linq; using System.Activities; using System.Activities.State ...
- 解决NO migrations to apply
创建表之后,遇到models模型变动,故当时做了删除应用文件夹下migrations文件,删除后重建,但重建后执行模型合并操作结果为No Changes,无法创建数据表 执行python3 manag ...
- 基于Python的机器学习实战:AadBoost
目录: 1. Boosting方法的简介 2. AdaBoost算法 3.基于单层决策树构建弱分类器 4.完整的AdaBoost的算法实现 5.总结 1. Boosting方法的简介 返回目录 Boo ...
- Linux RPM、YUM、APT包管理工具
⒈rpm包的管理 1)介绍 rpm是一种用于互联网下载包的打包及安装工具,它包含在某些Linux分发版中,它生成具有.RPM扩展名的文件,RPM是RedHat Package Manager(RedH ...
- Linux注销&登陆
⒈注销 ①在命令行使用logout,此指令在图形界面无效.
- 转载CSDN博客步骤
在参考“如何快速转载CSDN中的博客”后,由于自己不懂html以及markdown相关知识,所以花了一些时间来弄明白怎么转载博客,以下为转载CSDN博客步骤和一些知识小笔记. 参考博客原址:http: ...
- 【转】Windows下安装python2和python3双版本
[转]Windows下安装python2和python3双版本 现在大家常用的桌面操作系统有:Windows.Mac OS.ubuntu,其中Mac OS 和 ubuntu上都会自带python.这里 ...
- 异步编程之使用yield from
异步编程之使用yield from yield from 是 Python3.3 后新加的语言结构.yield from的主要功能是打开双向通道,把最外层的调用方法与最内层的子生成器连接起来.这两者就 ...
- Python3学习笔记12-定义函数及调用
函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段,能提高应用的模块性,和代码的重复利用率 Python提供了许多内建函数,比如print().也可以自己创建函数,这被叫做用户自定义函数 ...
- 如何理解深度学习中的Transposed Convolution?
知乎上的讨论:https://www.zhihu.com/question/43609045?sort=created 不过看的云里雾里,越看越糊涂. 直到看到了这个:http://deeplearn ...