参考: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()的更多相关文章

  1. 基类View

    尽管类视图看上去类的种类繁多,但每个类都是各司其职的,且从类的命名就可以很容易地看出这个类的功能.大致可分为如下三个大的功能块,分别由三个类提供对应的方法: 处理 HTTP 请求.根据 HTTP 请求 ...

  2. Django——基于类的视图(class-based view)

    刚开始的时候,django只有基于函数的视图(Function-based views).为了解决开发视图中繁杂的重复代码,基于函数的通用视图( Funcation-based generic vie ...

  3. django abstract base class ---- 抽象基类

    抽象蕨类用于定义一些同享的列.类本身并不会在数据库端有表与之对应 一.例子: 1.定义一个叫Person 的抽象基类.Student 继承自Person from django.db import m ...

  4. Django url中可以使用类视图.as_view()进行映射的原因

    说明:在练习天天生鲜项目时,对利用类视图去与正则匹配到的url做映射有点疑惑,经过查看他人博客以及自我分析算是整明白了,所以记录一下 参考:https://www.zmrenwu.com/post/5 ...

  5. django中抽象基类的Foreignkey的定义

    class base(models.Model): user = models.ForeignKey(User) class Meta: abstract =True 以上是抽象基类的定义,只有一个公 ...

  6. django(六):view和cbv

    FBV即以函数的形式实现视图函数,CBV即以类的形式实现视图函数:相比而言,CBV根据请求方式书写各自的代码逻辑,结构清晰明了,但是由于多了一层反射机制,性能要差一些:FBV执行效率要高一些,但是代码 ...

  7. Django——基于类的视图源码分析 二

    源码分析 抽象类和常用视图(base.py) 这个文件包含视图的顶级抽象类(View),基于模板的工具类(TemplateResponseMixin),模板视图(TemplateView)和重定向视图 ...

  8. DRF视图-基类

    2个视图基类 REST framework 提供了众多的通用视图基类与扩展类,以简化视图的编写. 为了区分上面请求和响应的代码,我们再次创建一个新的子应用: python manage.py star ...

  9. Django Function Based View(FBV)和Class Based View (CBV)对比

    一.FBV处理过程 首先来看一下FBV逻辑过程: 1.简单过程(借用官方示例): urls: from django.conf.urls import url from . import views ...

随机推荐

  1. Linux - 系统资源

    查看剩余内存 free -m #-/+ buffers/cache: #6458M为真实使用内存 1649M为真实剩余内存(剩余内存+缓存+缓冲器) #linux会利用所有的剩余内存作为缓存,所以要保 ...

  2. [洛谷P3948]数据结构 题解(差分)

    [洛谷P3948]数据结构 Description 最开始的数组每个元素都是0 给出n,opt ,min,max,mod 在int范围内 A: L ,R ,X 表示把[l,R] 这个区间加上X(数组的 ...

  3. UVA - 10480 Sabotage【最小割最大流定理】

    题意: 把一个图分成两部分,要把点1和点2分开.隔断每条边都有一个花费,求最小花费的情况下,应该切断那些边.这题很明显是最小割,也就是最大流.把1当成源点,2当成汇点,问题是要求最小割应该隔断那条边. ...

  4. 7、完整版的strcpy函数

    char * strcpy( char *strDest, const char *strSrc ) { assert( (strDest != NULL) && (strSrc != ...

  5. 设置PHPStorm 注释

    /** * Desc: xxx#if (${NAME}) * Class: ${NAME}#end#if (${NAMESPACE}) * Package: ${NAMESPACE}#end * Us ...

  6. ElasticSearch学习

    官方文档 https://www.elastic.co/cn/ http://www.learnes.net/

  7. POI导出带格式的Excel模板——(六)

    Jar包

  8. .NET中制做对象的副本(二)继承对象之间的数据拷贝

    定义学生 /// <summary> /// 学生信息 /// </summary> public class Student { /// <summary> // ...

  9. 【转载】Hadoop mapreduce 实现原理

    1.  如何用通俗的方法解释MapReduce MapReduce是Google开源的三大技术之一,是对海量数据进行“分而治之”计算框架.为了简单的理解并讲述给客户理解.我们举下面的例子来说明. 首先 ...

  10. GPIO推挽输出和开漏输出详解

    open-drain与push-pull] GPIO的功能,简单说就是可以根据自己的需要去配置为输入或输出.但是在配置GPIO管脚的时候,常会见到两种模式:开漏(open-drain,漏极开路)和推挽 ...