python学习笔记_week21
上节内容回顾:
1、请求周期
url> 路由 > 函数或类 > 返回字符串或者模板语言?
Form表单提交:
提交 -> url > 函数或类中的方法
- ....
HttpResponse('....')
render(request,'index.html')
redirect('/index/')
用户 < < 返回字符串
(当接受到redirect时)自动发起另外一个请求
--> url .....
Ajax:
$.ajax({
url: '/index/',
data: {'k': 'v', 'list': [1,2,3,4], 'k3': JSON.stringfy({'k1': 'v'}))}, $(form对象).serilize()
type: 'POST',
dataType: 'JSON':
traditional: true, #多选(如下拉框)要加traditional
success:function(data){ #回调函数
location.reload() # 刷新
location.href = "某个地址" # 跳转
}
})
提交 -> url -> 函数或类中的方法
HttpResponse('{}') #可定制性更高
render(request, 'index.html', {'name': 'v1'})
<h1>{{ name }}</h1> --> #用户拿到不能做特殊的处理
<h1>v1</h1>
XXXXXXX redirect...不可以 ,只能reload,href
用户 <<<<< 字符串
2、路由系统URL
a. /index/ -> 函数或类
b. /index/(\d+) -> 函数或类
c. /index/(?P<nid>\d+) -> 函数或类
d. /index/(?P<nid>\d+) name='root' -> 函数或类
reverse()
{% url 'root' 1%}
e. /crm/ include('app01.urls') -> 路由分发 f. 默认值
url(r'^index/', views.index, {'name': 'root'}), def index(request,name):
print(name)
return HttpResponse('OK')
g. 命名空间 #用于函数生成url
/admin/ include('app01.urls',namespace='m1')
/crm/ include('app01.urls',namespace='m2')
app01.urls
/index/ name = 'n1'
reverser('m1:n1')
3、
def func(request):
request.POST
request.GET
request.FILES
request.getlist
request.method
request.path_info
return render,HttpResponse,redirect
4、
render(request, 'index.html')
# for
# if
# 索引. keys values items all
5、
class User(models.Model):
username = models.CharField(max_length=32)
email = models.EmailField()
有验证功能
Django Admin
无验证功能:
User.objects.create(username='root',email='asdfasdfasdfasdf')
User.objects.filter(id=1).update(email='') class UserType(models.Model):
name = models.CharField(max_length=32)
class User(models.Model):
username = models.CharField(max_length=32)
email = models.EmailField()
user_type = models.ForeignKey("UserType")
user_list = User.objects.all()
for obj user_list: #对象列表
obj.username,obj.email,obj.user_type_id,obj.user_type.name,obj.user_type.id
user = User.objects.get(id=1) #单个对象
user.
User.objects.all().values("username","user_type__name",) #注意__ class UserType(models.Model):
name = models.CharField(max_length=32)
class User(models.Model):
username = models.CharField(max_length=32)
email = models.EmailField()
user_type = models.ForeignKey("UserType")
m = models.ManyToMany('UserGroup')
class UserGroup(models.Model):
name = ....
obj = User.objects.get(id=1)
obj.m.add(2)
obj.m.add(2,3)
obj.m.add(*[1,2,3])
obj.m.remove(...)
obj.m.clear()
obj.m.set([1,2,3,4,5])
obj.m.all() # 多个组,UserGroup对象
obj.m.filter(name='CTO')
知识点:
URL
- 两个
Views
- 请求的其他信息
from django.core.handlers.wsgi import WSGIRequest
request.environ
request.environ['HTTP_USER_AGENT']
- 装饰器
FBV:
def auth(func):
def inner(reqeust,*args,**kwargs):
v = reqeust.COOKIES.get('username111')
if not v:
return redirect('/login/')
return func(reqeust, *args,**kwargs)
return inner
CBV:
from django import views
from django.utils.decorators import method_decorator
@method_decorator(auth,name='dispatch')
class Order(views.View):
# @method_decorator(auth)
# def dispatch(self, request, *args, **kwargs):
# return super(Order,self).dispatch(request, *args, **kwargs)
# @method_decorator(auth)
def get(self,reqeust):
v = reqeust.COOKIES.get('username111')
return render(reqeust,'index.html',{'current_user': v})
def post(self,reqeust):
v = reqeust.COOKIES.get('username111')
return render(reqeust,'index.html',{'current_user': v})
Templates
- 母版...html ---可以模板渲染(会自动搞到一起再渲染)
extends 只能继承一个母版
include 可以有多个
- 自定义函数
simple_tag
a. app下创建templatetags目录 #templatetags目录名不能改
b. 任意xxoo.py文件
c. 创建template对象 register(对象名)不能改
d.
@register.simple_tag
def func(a1,a2,a3....)
return "asdfasd"
e. settings中注册APP
f. html顶部 {% load xxoo %}
g. {% 函数名 arg1 arg2 %} #空格没关系
缺点:
不能作为if条件
优点:
参数任意
filter
a. app下创建templatetags目录
b. 任意xxoo.py文件
c. 创建template对象 register
d.
@register.filter
def func(a1,a2)
return "asdfasd"
e. settings中注册APP
f. 顶部 {% load xxoo %}
g. {{ 参数1|函数名:"参数二,参数三" }} {{ 参数1|函数名:数字 }}
缺点:
最多两个参数,不能加空格
优点:
能作为if条件
分页(自定义的分页)
XSS:
{{ page_str|safe }} mark_safe(page_str)
cookie
客户端浏览器上的一个文件
{"user": 'dachengzi'}
参数:
key, 键
value='', 值
max_age=None, 超时时间
expires=None, 超时时间(IE requires expires, so set it if hasn't been already.)
path='/', Cookie生效的路径,/ 表示根路径,特殊的:跟路径的cookie可以被任何url的页面访问
domain=None, Cookie生效的域名
secure=False, https传输
httponly=False 只能http协议传输,无法被JavaScript获取(不是绝对,底层抓包可以获取到也可以被覆盖)
session :装饰器
Models
- 一大波操作
Form验证
-
缓存
中间件
信号
CSRF
Admin/ModelForm
作业:
主机管理:
1、单表操作
2、一对多
3、多对多
要求:
a. 删除对话框
b. 修改,添加新URL
c. 基于cookie进行用户认证
d. 定制显示个数
e. 分页
预习:
Form: http://www.cnblogs.com/wupeiqi/articles/6144178.html
Model:http://www.cnblogs.com/wupeiqi/articles/6216618.html
from django.shortcuts import render, HttpResponse,redirect
from django.urls import reverse
# Create your views here.
# def index(request):
# # v = reverse('author:index')
# # print(v)
# from django.core.handlers.wsgi import WSGIRequest
# # print(type(request))
# #封装了所有用户请求信息
# # print(request.environ)
# # for k,v in request.environ.items():
# # print(k,v)
# # print(request.environ['HTTP_USER_AGENT'])
# # request.POST
# # request.GET
# # request.COOKIES
#
# return HttpResponse('OK')
def tpl1(request):
user_list = [1, 2, 3, 43]
return render(request, 'tpl1.html', {'u': user_list})
def tpl2(request):
name = 'root'
return render(request, 'tpl2.html', {'name': name})
def tpl3(request):
status = "已经删除"
return render(request, 'tpl3.html', {'status': status})
def tpl4(request):
name = "IYMDFjfdf886sdf"
return render(request, 'tpl4.html', {'name': name})
from utils import pagination
LIST = []
for i in range(500):
LIST.append(i)
def user_list(request):
current_page = request.GET.get('p', 1) #1表示默认显示第一页
current_page = int(current_page)
val = request.COOKIES.get('per_page_count',10)
print(val)
val = int(val)
page_obj = pagination.Page(current_page,len(LIST),val)
data = LIST[page_obj.start:page_obj.end]
page_str = page_obj.page_str("/user_list/")
return render(request, 'user_list.html', {'li': data,'page_str': page_str})
########################### cookie ###########################
user_info = {
'dachengzi': {'pwd': ""},
'kanbazi': {'pwd': "kkkkkkk"},
}
def login(request):
if request.method == "GET":
return render(request,'login.html')
if request.method == "POST":
u = request.POST.get('username')
p = request.POST.get('pwd')
dic = user_info.get(u)
if not dic:
return render(request,'login.html')
if dic['pwd'] == p:
res = redirect('/index/')
# res.set_cookie('username111',u,max_age=10)
# import datetime
# current_date = datetime.datetime.utcnow()
# current_date = current_date + datetime.timedelta(seconds=5)
# res.set_cookie('username111',u,expires=current_date)
res.set_cookie('username111',u)
res.set_cookie('user_type',"asdfjalskdjf",httponly=True) #httponly用js获取不到
return res
else:
return render(request,'login.html')
def auth(func):
def inner(reqeust,*args,**kwargs):
v = reqeust.COOKIES.get('username111')
if not v:
return redirect('/login/')
return func(reqeust, *args,**kwargs)
return inner
@auth
def index(reqeust):
# 获取当前已经登录的用户
v = reqeust.COOKIES.get('username111')
return render(reqeust,'index.html',{'current_user': v})
from django import views
from django.utils.decorators import method_decorator
@method_decorator(auth,name='dispatch')
class Order(views.View):
# @method_decorator(auth)
# def dispatch(self, request, *args, **kwargs):
# return super(Order,self).dispatch(request, *args, **kwargs)
# @method_decorator(auth)
def get(self,reqeust):
v = reqeust.COOKIES.get('username111')
return render(reqeust,'index.html',{'current_user': v})
def post(self,reqeust):
v = reqeust.COOKIES.get('username111')
return render(reqeust,'index.html',{'current_user': v})
def order(reqeust):
# 获取当前已经登录的用户
v = reqeust.COOKIES.get('username111')
return render(reqeust,'index.html',{'current_user': v})
def cookie(request):
# request.COOKIES
# request.COOKIES['username111']
request.COOKIES.get('username111') #获取cookie
response = render(request,'index.html')
response = redirect('/index/')
response.set_cookie('key',"value")# 设置cookie,关闭浏览器失效
response.set_cookie('username111',"value",max_age=10)# 设置cookie, N秒只有失效
import datetime
current_date = datetime.datetime.utcnow()
current_date = current_date + datetime.timedelta(seconds=5)
response.set_cookie('username111',"value",expires=current_date) # 设置cookie, 截止时间失效
response.set_cookie('username111',"value",max_age=10)
# request.COOKIES.get('...')
# response.set_cookie(...)
obj = HttpResponse('s')
obj.set_signed_cookie('username',"kangbazi",salt="asdfasdf") #加密文
request.get_signed_cookie('username',salt="asdfasdf") #解密
return response
from django.conf.urls import url,include
from django.contrib import admin
from app01 import views
urlpatterns = [
# url(r'^admin/', admin.site.urls),
# url(r'^index/', views.index),
# url(r'^index/', views.index, {'name': 'root'}),
# url(r'^a/', include('app01.urls', namespace='author')),
url(r'^tpl1/', views.tpl1),
url(r'^tpl2/', views.tpl2),
url(r'^tpl3/', views.tpl3),
url(r'^tpl4/', views.tpl4),
url(r'^user_list/', views.user_list),
url(r'^login/', views.login),
url(r'^index/', views.index),
url(r'^order/', views.Order.as_view()),
]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>欢迎登录:{{ current_user }}</h1>
</body>
</html>
<li>{{ item }}</li>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="/login/" method="POST">
<input type="text" name="username" placeholder="用户名" />
<input type="password" name="pwd" placeholder="密码" />
<input type="submit" />
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %} {% endblock %}</title>
<link rel="stylesheet" href="/static/commons.css" />
<style>
.pg-header{
height: 50px;
background-color: seashell;
color: green;
}
</style>
{% block css %} {% endblock %}
</head>
<body>
<div class="pg-header">小男孩管理</div>
<div>
<a>asdf</a>
<a id="">asdf</a>
<a>asdf</a>
<a>asdf</a>
<a>asdf</a>
</div>
<iframe src="/"></iframe>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="/static/commons.css" />
<style>
.pg-header{
height: 48px;
background-color: seashell;
color: green;
}
</style>
</head>
<body>
<div class="pg-header">小男孩管理</div>
<h1>用户管理</h1>
<ul>
{% for i in u %}
<li>{{ i }}</li>
{% endfor %}
</ul>
<script src="/static/jquery.js"></script>
</body>
</html>
{% extends 'master.html' %}
{% block title %}用户管理{% endblock %}
{% block content %}
<h1>用户管理</h1>
<ul>
{% for i in u %}
<li>{{ i }}</li>
{% endfor %}
</ul>
{% for i in u %}
{% include 'tag.html' %}
{% endfor %}
{% endblock %}
{% block css %}
<style>
body{
background-color: red;
}
</style>
{% endblock %}
{% block js %}
<script></script>
{% endblock %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="/static/commons.css" />
<style>
.pg-header{
height: 48px;
background-color: seashell;
color: green;
}
</style>
</head>
<body>
<div class="pg-header">小男孩管理</div>
<h1>修改密码{{ name }}</h1>
<script src="/static/jquery.js"></script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="/static/commons.css" />
<style>
.pg-header{
height: 48px;
background-color: seashell;
color: green;
}
</style>
</head>
<body>
<div class="pg-header">小女孩管理</div>
<h3> {{ status }}</h3>
<script src="/static/jquery.js"></script>
</body>
</html>
{% load xxoo %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
{{ name }}
{{ name|lower }}
{{ name|truncatechars:"3" }}
{% houyafan 2 5 6 %}
{{ "maliya"|jiajingze:30 }}
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
.pagination .page{
display: inline-block;
padding: 5px;
background-color: cyan;
margin: 5px;
}
.pagination .page.active{
background-color: brown;
color: white;
}
</style>
</head>
<body>
<ul id="len">
{% for item in li %}
{% include 'li.html' %}
{% endfor %}
</ul>
<div>
<select id="ps" onchange="changePageSize(this)">
<option value="10">10</option>
<option value="30">30</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
</div>
<div class="pagination">
{{ page_str }}
</div>
<script src="/static/jquery-1.12.4.js"></script>
<script src="/static/jquery.cookie.js"></script>
<script>
$(function(){
var v = $.cookie('per_page_count',$("#len li").length,{'path': "/user_list/`"});
console.log(v);
$('#ps').val($("#len li").length);
});
function changePageSize(ths){
var v = $(ths).val();
console.log(v);
$.cookie('per_page_count',v, {'path': "/user_list/"});
location.reload();
}
</script>
</body>
</html>
from django.utils.safestring import mark_safe
class Page:
def __init__(self, current_page, data_count, per_page_count=10, pager_num=7):
self.current_page = current_page
self.data_count = data_count
self.per_page_count = per_page_count
self.pager_num = pager_num
@property
def start(self):
return (self.current_page - 1) * self.per_page_count
@property
def end(self):
return self.current_page * self.per_page_count
@property
def total_count(self):
v, y = divmod(self.data_count, self.per_page_count)
if y:
v += 1
return v
def page_str(self, base_url):
page_list = []
if self.total_count < self.pager_num:
start_index = 1
end_index = self.total_count + 1
else:
if self.current_page <= (self.pager_num + 1) / 2:
start_index = 1
end_index = self.pager_num + 1
else:
start_index = self.current_page - (self.pager_num - 1) / 2
end_index = self.current_page + (self.pager_num + 1) / 2
if (self.current_page + (self.pager_num - 1) / 2) > self.total_count:
end_index = self.total_count + 1
start_index = self.total_count - self.pager_num + 1
if self.current_page == 1:
prev = '<a class="page" href="javascript:void(0);">上一页</a>'
else:
prev = '<a class="page" href="%s?p=%s">上一页</a>' % (base_url, self.current_page - 1,)
page_list.append(prev)
for i in range(int(start_index), int(end_index)):
if i == self.current_page:
temp = '<a class="page active" href="%s?p=%s">%s</a>' % (base_url, i, i)
else:
temp = '<a class="page" href="%s?p=%s">%s</a>' % (base_url, i, i)
page_list.append(temp)
if self.current_page == self.total_count:
nex = '<a class="page" href="javascript:void(0);">下一页</a>'
else:
nex = '<a class="page" href="%s?p=%s">下一页</a>' % (base_url, self.current_page + 1,)
page_list.append(nex)
jump = """
<input type='text' /><a onclick='jumpTo(this, "%s?p=");'>GO</a>
<script>
function jumpTo(ths,base){
var val = ths.previousSibling.value;
location.href = base + val;
}
</script>
""" % (base_url,)
page_list.append(jump)
page_str = mark_safe("".join(page_list))
return page_str
python学习笔记_week21的更多相关文章
- python学习笔记整理——字典
python学习笔记整理 数据结构--字典 无序的 {键:值} 对集合 用于查询的方法 len(d) Return the number of items in the dictionary d. 返 ...
- VS2013中Python学习笔记[Django Web的第一个网页]
前言 前面我简单介绍了Python的Hello World.看到有人问我搞搞Python的Web,一时兴起,就来试试看. 第一篇 VS2013中Python学习笔记[环境搭建] 简单介绍Python环 ...
- python学习笔记之module && package
个人总结: import module,module就是文件名,导入那个python文件 import package,package就是一个文件夹,导入的文件夹下有一个__init__.py的文件, ...
- python学习笔记(六)文件夹遍历,异常处理
python学习笔记(六) 文件夹遍历 1.递归遍历 import os allfile = [] def dirList(path): filelist = os.listdir(path) for ...
- python学习笔记--Django入门四 管理站点--二
接上一节 python学习笔记--Django入门四 管理站点 设置字段可选 编辑Book模块在email字段上加上blank=True,指定email字段为可选,代码如下: class Autho ...
- python学习笔记--Django入门0 安装dangjo
经过这几天的折腾,经历了Django的各种报错,翻译的内容虽然不错,但是与实际的版本有差别,会出现各种奇葩的错误.现在终于找到了解决方法:查看英文原版内容:http://djangobook.com/ ...
- python学习笔记(一)元组,序列,字典
python学习笔记(一)元组,序列,字典
- Pythoner | 你像从前一样的Python学习笔记
Pythoner | 你像从前一样的Python学习笔记 Pythoner
- OpenCV之Python学习笔记
OpenCV之Python学习笔记 直都在用Python+OpenCV做一些算法的原型.本来想留下发布一些文章的,可是整理一下就有点无奈了,都是写零散不成系统的小片段.现在看 到一本国外的新书< ...
随机推荐
- 关键两招就解决Wampserver 打开localhost显示IIS7图片问题
我们在安装集成环境Wampserver之后,有时会遇到一个问题, 打开localhost显示一张IIS7图片,这个问题该如何解决呢,我在网上找了一些说的都很乱,我在这里简单整理了一下解决方法 1 ...
- 黄聪:PHP数据库连接失败--could not find driver 解决办法
数据库连接失败could not find driver在调试一个PHP程序时,报了这个错误, could not find driver 经过一番查找,结合自己的思考和实践,终于找到了问题所在. 原 ...
- mvc 缓存 sqlCacheDependency 监听数据变化
mvc 缓存 对于MVC有Control缓存和Action缓存. 一.Control缓存 Control缓存即是把缓存应用到整个Control上,该Control下的所有Action都会被缓存起来 ...
- PHP批量添加数据
<?php // 连接数据库 header('content-type:text/html;charset=utf-8'); define('DB_HOST','127.0.0.1'); def ...
- 关于Dubbo面试问题
一.默认使用的是什么通信框架,还有别的选择吗? 默认也推荐使用netty框架,还有mina. 二.服务调用是阻塞的吗? 默认是阻塞的,可以异步调用,没有返回值的可以这么做. 三.一般使用什么注册中心? ...
- Java 线程转储 [转]
http://www.oschina.net/translate/java-thread-dump java线程转储 java的线程转储可以被定义为JVM中在某一个给定的时刻运行的所有线程的快照.一个 ...
- P1616疯狂的采药
传送 它不是可爱的01背包了!!!这个题中一种药可以采无限次!!! 它进化成了完全背包.完全背包中的内循环从m到v[i]改成了从v[i]到m 既然如此,代码如下: #include<iostre ...
- Java 基础面试题
1.一个".java"源文件中是否可以包括多个类(不是内部类)?有什么限制? 可以有多个类,但只能有一个public的类,并且public的类名必须与文件名一致 2.Java有没有 ...
- 字符串分割split()
知识讲解: split() 方法将字符串分割为字符串数组,并返回此数组. 语法: stringObject.split(separator,limit) 参数说明: 注意:如果把空字符串 (" ...
- 廖雪峰Java2-2数据封装-2构造方法
在2-2-1中,创建1个实例需要3步 Person ming = new Person(); ming.setName(" 小明 "); ming.setAge(16); 问题:能 ...