惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
News | PayPal Newsroom
云风的 BLOG
云风的 BLOG
GbyAI
GbyAI
Engineering at Meta
Engineering at Meta
B
Blog RSS Feed
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
The Register - Security
The Register - Security
L
LangChain Blog
A
About on SuperTechFans
S
Schneier on Security
博客园 - 三生石上(FineUI控件)
Stack Overflow Blog
Stack Overflow Blog
The Hacker News
The Hacker News
AWS News Blog
AWS News Blog
博客园 - 司徒正美
Scott Helme
Scott Helme
K
Kaspersky official blog
Cyberwarzone
Cyberwarzone
T
Tenable Blog
腾讯CDC
Recorded Future
Recorded Future
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
G
GRAHAM CLULEY
Security Latest
Security Latest
S
Securelist
D
Darknet – Hacking Tools, Hacker News & Cyber Security
aimingoo的专栏
aimingoo的专栏
Google DeepMind News
Google DeepMind News
V
Vulnerabilities – Threatpost
雷峰网
雷峰网
T
The Exploit Database - CXSecurity.com
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
V
V2EX
T
The Blog of Author Tim Ferriss
D
Docker
S
Security Affairs
F
Full Disclosure
Know Your Adversary
Know Your Adversary
N
News and Events Feed by Topic
N
News and Events Feed by Topic
T
Tor Project blog
Hugging Face - Blog
Hugging Face - Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Microsoft Security Blog
Microsoft Security Blog
Simon Willison's Weblog
Simon Willison's Weblog
Recent Announcements
Recent Announcements
博客园_首页
博客园 - 聂微东
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
S
Security @ Cisco Blogs

陈少文的网站

巨变与机遇的未来十年 Kubernetes 平台管理软件压力测试方案 使用镜像部署 Hexo 静态页面 终于等到你 - GitHub 镜像仓库服务(ghcr.io) 一起来学 Go --(6)Interface 一起来学 Go --(5)Goroutine 和 Channel 什么是函数式编程 如何在 Kubernetes 集群集成 Kata 柯里化与偏函数 使用 PyGithub 自动创建 Label 软件产品是团队能力的输出 Helm 2 、Helm 3 比较 IoT 变现 Kubernetes 中的 DNS 服务 国内的 Helm 镜像源 Harbor 使用自签证书支持 Https 访问 DevOps 工具链之 Prow 如何使用 kfctl 安装 Kubeflow VS Code 无法下载 Go 插件的工具包 工程师更应具有服务精神 你不知道的 Docker 使用技巧 使用 Docker 运行 Tensorflow 论中国 什么是左移 如何清空 Git 仓库全部历史记录 一禅小和尚 有风吹过厨房 时间的玫瑰 如何在 CentOS 安装 GPU 驱动 开发 Tips(19) 使用 Velero 备份 Kubernetes 集群 Kubernetes Cheat Sheet 开发 Tips(18) 如何构建一个 Java 工程 开发 Tips(17) KubeSpray 安装 Kubernetes 报错 ip in ansible_all_ipv4_addresses 基于 Kubernetes 和 Jenkins 搭建自动化测试系统 在 Kubernetes 上动态创建 Jenkins Slave 使用 Jenkins 进行服务拨测 开发 Tips(16) Kubernetes 签发 Ingress 证书及日常故障运维 Kubernetes 中 Deployment 的基本操作 Kubernetes 中的证书 如何使用 KubeBuilder 开发一个 Operator Kubernetes 1.6.0 安装问题汇总 镜像管理工具 -- Harbor 开发 Tips(15) Docker 如何拉取镜像 开发 Tips(14) 使用 Helm 安装 harbor 开发 Tips(13) 使用 S2I 构建云原生应用 在 Kubernetes 中使用 emptyDir、hostPath、localVolume 开发 Tips(12) 开发 Tips(11) 代码质量分析工具 SonarQube 使用 Kubeadm 安装 Kubernetes 集群 一起来学 Go --(4)常用函数 Kubernetes 中的 Ceph Kubernetes 之 Volumes Kubernetes 之 Labels、Selectors 开发 Tips(10) 开源正在重构商业模式 Kubernetes 之网络 Kubernetes 之 API 使用 Helm 和 Operator 快速部署 Prometheus Kubernetes 复杂有状态应用管理框架 -- Operator Kubernetes 的包管理器 -- Helm 一起来学 Go --(3)Go Modules 如何一步一步地优化博客方案 kubectl 实用指南 Kubernetes 中的基本概念 搭建远程 Kubernetes 开发环境 大公司和小公司的 ToB 思路 开发 Tips(9) Go 入门指南 一起来学 Go --(2)数据与逻辑结构 如何预防 Web 富文本中的 XSS 攻击 django-xss-cleaner 云工作时代 一起来学 Go --(1)背景与特点 SaaS 开发团队的不同阶段 你不知道的 Git 使用技巧 输出既服务 微服务设计 继续奔跑 开发 Tips(8) 从账户安全到二次验证 Django 性能之数据库查询优化 Django 性能之分库分表 敏捷开发之研发流程 打造一致性的团队 开发 Tips(7) Pytest 进阶学习之 Mock PaaS 部署之 buildpack Go 开发配置 领域输出才是 PaaS 的核心竞争力 Pytest 入门学习 开发 Tips(6) 如何使用 Jenkins、Docker、GitLab 搭建 Django 自动化部署流程
Django 类视图
微信公众号 · 2017-07-12 · via 陈少文的网站

Please enable Javascript to view the contents

Django中有两种视图,一种是函数式视图,另一种是类视图。视图的作用主要是,用于填充逻辑,返回响应体。函数式视图难以扩展,代码复用率低。而类视图可以利用继承、Mixins,快速复用、扩展功能。本文主要讨论了,Django对类视图的处理逻辑,类视图装饰器实现。

1. Django的视图

Django的URL解析器,将一个HttpRequest对象和相应的参数传递给一个可调用的函数,并期待其返回一个HttpResponse对象。这个可调用的函数,就是视图函数。

1.1 函数式视图

views.py

1
2
3
4
5
6
7
8
9
from django.http import HttpResponse

def my_view(request):
    if request.method == 'GET':
        # 填充逻辑
        return HttpResponse('result')
    if request.method == 'POST':
        # 填充逻辑
        return HttpResponse('result')

urls.py

1
2
3
4
5
6
7
# urls.py
from django.conf.urls import patterns
import .views as home_view

urlpatterns = patterns('',
    (r'^my_view/', home_view.my_view)
)

函数式视图(FBV)只使用在定制错误,或那些使用类视图实现时会很复杂的情况。

1.2 类视图

views.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from django.http import HttpResponse
from django.views.generic.base import View

class MyView(View):
    def get(self, request):
        # 填充逻辑
        return HttpResponse('result')
    def post(self, request):
        # 填充逻辑
        return HttpResponse('result')

urls.py

1
2
3
4
5
6
7
# urls.py
from django.conf.urls import patterns
from .views import MyView

urlpatterns = patterns('',
    (r'^about/', MyView.as_view()),
)

为了解耦视图和URL、代码复用,Django提供了类视图。

类视图(CBV)提供了一个as_view()静态方法,调用该方法,会创建一个类的实例。然后调用实例的dispatch()方法,dispatch()方法会根据request的请求类型,调用相应实例的同名方法。如果没有找到对应的方法,将引发一个HttpResponseNotAllowed异常。

Django提供的一系列类视图类,都继承自一个View基类(django.views.generic.base.View),在这个基类里实现了与 URL的接口(as_view)、请求方法匹配(dispatch)和一些其他的基本功能。比如 ,RedirectView 实现了 HTTP 重定向,TemplateView 新增了渲染模板的方法。

django.views.generic.base.py 中View类as_view和dispatch方法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@classonlymethod
def as_view(cls, **initkwargs):
    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)

    update_wrapper(view, cls, updated=())

    update_wrapper(view, cls.dispatch, assigned=())
    return view

def dispatch(self, request, *args, **kwargs):
    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)

2. Django视图Mixin类

Django将基本的HTTP请求和响应,抽象封装成类。在使用过程中,只需要将这些基类聚合,按照需求的方式重写或者直接复用。这些基类称之为Mixin。

在django.views.generic包中,除了base提供了构成cbv最基础的几个Mixin,以及cbv的基类View,还提供了四个模块,

  • detail,显示详细数据,SingleObjectMixin,SingleObjectTemplateResponseMixin
  • list,显示列表,MultipleObjectMixin,MultipleObjectTemplateResponseMixin
  • edit,提供新增和编辑的功能,DeletionMixin,FormMixin,
  • dates,年月日相关的显示和获取,YearMixin, MonthMixin, DayMixin, WeekMixin, DateMixin

一个View Class可以继承多个Mixin,但是只能继承一个View(包括其子类)。

3. 类视图装饰器

3.1 修饰dispatch

dispatch装饰器,将影响到全部的视图类方法函数。Django 1.9开始method_decorator支持name参数,可以指定方法,例如,name=‘get’,表示仅修饰get函数。如果有多个装饰器需要配置,@method_decorator也接受列表参数,可以同时装配多个装饰器。

1
2
3
4
5
6
7
8
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic.base import View

class MyView(View):
    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(MyView, self).dispatch(*args, **kwargs)

带参数的装饰器用法:
@method_decorator(login_required_by_role(‘super’))

3.2 修饰视图类

修饰类和修饰dispatch一样,也会影响全部HTTP方法。

1
2
3
4
5
6
7
8
9
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic.base import View

@method_decorator(login_required)
class MyView(View):

    def dispatch(self, *args, **kwargs):
        return super(MyView, self).dispatch(*args, **kwargs)

3.3 URLConf中配置装饰器

1
2
3
4
5
6
7
8
9
from django.contrib.auth.decorators import login_required, permission_required
from django.views.generic import TemplateView

from .views import VoteView

urlpatterns = [
    url(r'^about/$', login_required(TemplateView.as_view(template_name="secret.html"))),
    url(r'^vote/$', permission_required('polls.can_vote')(VoteView.as_view())),
]

4. 参考


微信公众号