Python学习---django知识补充之CBV
Django知识补充之CBV
Django:
url --> def函数 FBV[function based view] 用函数和URL进行匹配
url --> 类 CBV[function based view] 用类和URL进行匹配
POSTMAN插件
http://blog.csdn.net/zzy1078689276/article/details/77528249
基于CBV的登录实例:
settings.py
INSTALLED_APPS = [
...
'app01', # 注册app
]
STATICFILES_DIRS = (os.path.join(BASE_DIR, "statics"),) # 现添加的配置,这里是元组,注意逗号
TEMPLATES = [
...
'DIRS': [os.path.join(BASE_DIR, 'templates')],
]
urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
from app01 import views
urlpatterns = [
# 基于CBV的登录
# url(r'^login.html/', views.login), # 原来基于函数
url(r'^login.html/', views.Login.as_view()), # 现在基于类名.as_view()
]
views.py
from django.shortcuts import render, redirect
from app01 import models
# 基于CBV的登录,需要导入views
from django import views
class Login(views.View):
# http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
def get(self, request, *args, **kwargs):
print(request.method, 'GGGGGGGGGGGG')
message = ''
return render(request, 'login.html', {'message': message}) # 这里是网页html
def post(self, request, *args, **kwargs):
print(request.method, 'OOOOOOOOOOOOO')
username = request.POST.get("user")
password = request.POST.get("pass")
print('username: %s, password:%s' % (username, password))
# obj = models.Administrator.objects.filter(username=username, password=password).count()
# if obj: 从数据库内取出数据,进行判断也可以
if username == 'root' and password == 'root':
req = redirect('/index.html/') # 接收redirect对象,# 这里是浏览器路径,伪静态
# req.set_cookie('username', username, max_age=10) # 设置超时时间10s
import datetime
timeout = datetime.datetime.now() + datetime.timedelta(seconds=10)
req.set_cookie('username', username, max_age=10, expires=timeout)
# IE设置超时时间10s
return req
# return redirect('/index.html') # 与上面3行同,只是添加了Cookie
else:
message = '用户名或密码错误'
return render(request, 'login.html', {'message': message}) # 这里是网页html
templates/login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{# 伪静态#}
<form action="/login.html/" method="post">
{% csrf_token %} {# 为跨站请求 #}
<div>
<label for="user">用户名</label>
<input id="user" name="user" type="text">
</div>
<div>
<label for="pass">密 码</label>
<input id="pass" name="pass" type="password">
</div>
<div>
<label></label>
<input value="登录" type="submit">
<span style="color: red">{{ message }}</span>
</div>
</form>
</body>
</html>
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<h2>hello, {{ username }}</h2>
</body>
</html>
页面显示:

CBV基于装饰器的使用<一> ---基于Python旧方法
CBV基于装饰器的使用<一> ---基于Python旧方法
装饰器:函数执行之前/后可以增加扩展功能
有多个方法的时候,必须给每个方法添加装饰器哈
CBV的反射原理

单一装饰器
views.py
from django.shortcuts import render, redirect
from app01 import models
# 基于CBV的登录,需要导入views
from django import views
from django.utils.decorators import method_decorator # 导入装饰器
# 基于CBV的装饰器的使用
def outer(func):
def inner(request, *args, **kwargs):
print(request.method)
return func(request, *args, **kwargs)
return inner class Login(views.View):
# http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
@method_decorator(outer)
def get(self, request, *args, **kwargs):
message = ''
return render(request, 'login.html', {'message': message}) # 这里是网页html @method_decorator(outer)
def post(self, request, *args, **kwargs):
username = request.POST.get("user")
password = request.POST.get("pass")
print('username: %s, password:%s' % (username, password))
# obj = models.Administrator.objects.filter(username=username, password=password).count()
# if obj: 从数据库内取出数据,进行判断也可以
if username == 'root' and password == 'root':
req = redirect('/index.html/') # 接收redirect对象,# 这里是浏览器路径,伪静态
# req.set_cookie('username', username, max_age=10) # 设置超时时间10s
import datetime
timeout = datetime.datetime.now() + datetime.timedelta(seconds=10)
req.set_cookie('username', username, max_age=10, expires=timeout)
# IE设置超时时间10s
return req
# return redirect('/index.html') # 与上面3行同,只是添加了Cookie
else:
message = '用户名或密码错误'
return render(request, 'login.html', {'message': message}) # 这里是网页html
CBV基于装饰器的使用<二> --基于Django的dispatch[多个装饰器]
CBV基于装饰器的使用<二> --基于Django的dispatch[多个装饰器]
如果对某一种请求做处理: 单一装饰器
如果对所有的请求做处理: dispatch单一装饰器
添加装饰器有2中方法:
1.类上添加
2.方法上添加

自定义转发dispatch函数
from django import views
from django.utils.decorators import method_decorator # 导入装饰器
class Login(views.View):
# http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
# 自定义转发器,URL进来都在此处进行URL转发,我们可以有一些预操作[函数验证可以放此处]
def dispatch(self, request, *args, **kwargs):
print('自定义dispatch: 前')
# if request.method == 'POST':
# return HttpResponse("Good Bye") # 预操作处理
# 请求先到Login的dispatch,然后调用父类的dispatch,返回结果给了obj
obj = super(Login, self).dispatch(request, *args, **kwargs) # 自定义转发且调用父类dispatch
# 将父类的返回结果返回给界面,否则界面报错
print('自定义dispatch: 后')
return obj def get(self, request, *args, **kwargs):
message = ''
return render(request, 'login.html', {'message': message}) # 这里是网页html
...同上

Python学习---django知识补充之CBV的更多相关文章
- 【python学习小知识】求绝对值和numpy和tensor的相互转换
一.python求绝对值的三种方法 1.条件判断 2.内置函数abs() 3.内置模块 math.fabs 1.条件判段,判断大于0还是小于0,小于0则输出相反数即可 # 法1:使用条件判断求绝对值 ...
- Python学习---django模板语法180122
django模板语法[Template] 模版的组成: HTML代码+逻辑控制代码 <h1> {{ user_name }} </h1> 逻辑控制代码的组成: 1.变量: ...
- Python学习---Django下的Sql性能的测试
安装django-debug-tools Python学习---django-debug-tools安装 性能测试: settings.py INSTALLED_APPS = [ ... 'app01 ...
- python学习-- Django根据现有数据库,自动生成models模型文件
Django引入外部数据库还是比较方便的,步骤如下 : 创建一个项目,修改seting文件,在setting里面设置你要连接的数据库类型和连接名称,地址之类,和创建新项目的时候一致 运行下面代码可以自 ...
- Django知识补充
目录 一.文件上传 二.Models补充 三.Django总结 一.文件上传 1.通过form表单或者通过From类上传 views.py from django.shortcuts import r ...
- Python之Django rest_Framework补充
一.什么是RESTful REST与技术无关,代表的是一种软件架构风格,REST是Representational State Transfer的简称,中文翻译为"表征状态转移" ...
- Python学习---django下的cookie操作 180201
什么是Cookies 什么是Cookies cookies设置的原因: 1. http请求的无记忆性: 2.加快访问速度 3. 减少服务器压力 cookies特点: cookies保存在客户端浏览器 ...
- Python学习---django之ORM语法[对象关系映射]180124
ORM语法[对象关系映射] ORM: 用面向对象的方式去操作数据库的创建表以及增删改查等操作. 优点:1 ORM使得我们的通用数据库交互变得简单易行,而且完全不用考虑该死的SQL语句.快速开发. 2 ...
- Python学习---Django的基础学习
django实现流程 Django学习框架: #安装: pip3 install django 添加环境变量 #1 创建project django-ad ...
随机推荐
- ASP.NET站点部署相关
汤姆大叔的部署指南:http://www.cnblogs.com/TomXu/archive/2011/11/25/2263050.html 中文目录: 部署介绍 --(英文版连接) 部署SQL Se ...
- 用尾递归和普通递归实现n!算法,二者比较
尾递归 - Tail Recursion尾递归是针对传统的递归算法而言的, 传统的递归算法在很多时候被视为洪水猛兽. 它的名声狼籍, 好像永远和低效联系在一起.尾递归就是从最后开始计算, 每递归一次就 ...
- canvas的measureText()方法
做一个小动画的时候遇到了个问题,就是在给文字应用渐变色的时候,不知怎么设置渐变色的区域. 渐变依赖于定义时的区域,超出这个区域只有纯色,而不是渐变色. 所以要取得文字的宽度. 查了资料得知,canva ...
- Rechnernetz
1.Der Aufbau des Internets 1.1 Randabschnitt Er besteht aus Rechner,der mit Internet verbunden ist.D ...
- 如何用webgl(three.js)搭建不规则建筑模型,客流量热力图模拟
本节课主要讲解如何用webgl(three.js)搭建一个建筑模型,客流量热力图模拟 使用技术说明: 这里主要用到了three.js,echart.js以及一些其它的js 与css技术,利用webso ...
- C#实现文件下载的几种方式
上篇博客也说了下C#中通过XML导出Excel,这些文件操作都挺有用的,下面是文件的下载,之前做项目都是把它写的空间日志中,以后有时间了把它们都弄出来 先把有问题的代码贴出来吧 using Syste ...
- laravel5.4学习--laravel基本路由
最基本的 Laravel 路由只接收一个 URI 和一个闭包,并以此提供一个非常简单且优雅的定义路由方法: Route::get('foo', function () {return 'Hello W ...
- DataGridView 单元格自动填充
在DataGridView单元格中,当输入指定字符时,自动完成填充. 通过 TextBox实现 AutoCompleteMode AutoCompleteMode.Suggest: AutoCompl ...
- 四、spark集群架构
spark集群架构官方文档:http://spark.apache.org/docs/latest/cluster-overview.html 集群架构 我们先看这张图 这张图把spark架构拆分成了 ...
- JavaMail获取已发送邮件
public static void main(String args[]) { Properties props = new Properties(); // 参数配置 props.setPrope ...