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 ...
随机推荐
- Django-Model操作数据库(增删改查、连表结构)
一.数据库操作 1.创建model表 基本结构 1 2 3 4 5 6 from django.db import models class userinfo(models.M ...
- 【文件】java生成PDF文件
package test; import java.awt.Color; import java.io.FileOutputStream; import org.junit.Test; import ...
- sqlite limit offset
limit 0,20 表示从第1条开始取20条数据 limit 20 offset 2 表示从第2条开始取出20条数据
- 从Nexus私服下载和上传资源(一)
从私服中下载资源 首先要明确将资源下载到哪里 找到maven 配置文件settings.xml 文件,添加如下配置:1.添加镜像配置:将所有访问外网仓库的请求指向私服: <mirror> ...
- JNI打通java和c
1.JNI简介 The Java Native Interface (JNI) is a programming framework that enables Java code running in ...
- ubuntu + usb转RS232驱动
1. 购买USB转串RS232/485/422 如果你的电脑有串口的话,就不用买啦,我的台式机有串口,把USB转串的线插上之后,unbuntu就不支持了.(自己有嘛) 就是输入 ls /dev/tt ...
- Python|绝不乱入的靠谱书单
- NMS和soft-nms算法
非极大值抑制算法(nms) 1. 算法原理 非极大值抑制算法(Non-maximum suppression, NMS)的本质是搜索局部极大值,抑制非极大值元素. 2. 3邻域情况下NMS的实现 3邻 ...
- UML和模式应用5:细化阶段(9)---迈向对象设计
1.前言 开发者如何设计对象,可以采用如下三种方式: 编码:在编码的同时进行设计 绘图然后编码:绘制一些UML,然后转到如上编码方式,在集成开发环境中编码 只绘图,不编码:使用工具从图中生成一切 本章 ...
- java多线程系列五、并发容器
一.ConcurrentHashMap 1.为什么要使用ConcurrentHashMap 在多线程环境下,使用HashMap进行put操作会引起死循环,导致CPU利用率接近100%,HashMap在 ...