Django学习之 - 基础视图函数
视图:Views
获取用户请求的方法:
1: request.GET
2: request.POST
3: request.FILES
# checkbox 等多选文件
4:request.POST.getlist()
# 上传文件,form标签要做特殊设置
obj = request.FILES.get('fafafa')
obj.name 上传的文件名
obj.chunks() 上传的文件内容
f = open(obj.name,mode='wb')
for item in obj.chunks():
f.write(item)
f.close()
实例:注册register视图函数
def register(request):
if request.method == 'GET':
return render(request,'register.html')
elif request.method == 'POST':
uname = request.POST.get('username',None)
upwd = request.POST.get('pwd',None)
print('用户名:',uname,'密码:',upwd)
ugender = request.POST.get('gender',None)
print('性别:', ugender)
ufavor = request.POST.getlist('favor',None)
print('爱好:',ufavor)
ucity = request.POST.getlist('city',None)
print('城市:',ucity)
obj = request.FILES.get('upfile')
tmppath = os.path.join('upload',obj.name)
f = open(tmppath,mode='wb')
for item in obj.chunks():
f.write(item)
return HttpResponse('注册完毕')
else:
return redirect('/register')
5:request.method
6:request.path_info
7:request.COOKIES
request.body # 所有提交的数据的原生值
- request.POST
- request.GET
- request.FILES
- request.xxx.getlist
request.Meta # 获取提交的数据的请求头信息,如客户端游览器这里可以提取到
- request.method(POST,GET,PUT)
- request.path_info
- request.COOKIES
返回3种:
return HttpResponse('字符串或者字节')
return render()
return redirect()
返回cookie,并且可以自定义添加响应头返回给客户端,客户端游览器可以在响应头查看到返回的值
response = HttpResponse('china')
response['name'] = jack
response.set_cookie()
return response
FBV & CBV
FBV ( function base view) :就是在视图里使用函数处理请求。
/index ==> 函数
CBV ( class base view) :就是在视图里使用类处理请求
/index ==> 类
实例cbv写法:
urls写法:
url(r'^cbv',views.cbv.as_view()), 视图函数:
class cbv(View):
def dispath(self,request,*args,**kwargs):
# 调用父类中的dispath
print('before')
result = super(cbv,self).dispatch(request,*args,**kwargs)
print('after')
return result
def get(self,request):
print(request.method)
return render(request,'CBV.html')
def post(self,request):
print(request.method,'POST')
return render(request,'CBV.html')
CBV
建议:俩者都用
CBV / FBV 装饰器
FBV 装饰器:
def auth(func):
def inner(request,*args,**kwargs):
v = request.COOKIES.get('uname')
if not v:
return redirect('/ug/login')
return func(*args,**kwargs)
return inner
CBV 装饰器:
from django import views
from django.utils.decorators import method_decorator
class Order(views.View):
@method_decorator(auth)
def get(self,request):
v = request.COOKIES.get('uname')
return render(request,'index.html',{'current_user':v})
def post(self,request):
v = request.COOKIES.get('uname')
return render(request,'index.html',{'current_user':v})
- 获取请求的其他信息
通过pring(type(request))获取模块文件名
from django.core.handlers.wsgi import WSGIRequest
request.environ # 输出请求的所有信息
request.environ['HTTP_USER_AGENT'] # 获取http_user_agent数据
通过以上方法提取环境数据
- 分页(自定义)
XSS:
前台:{{ page_str|safe }}
后台:mark_safe(page_str)
分页实例:
html页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>分页</title>
<style>
.page {
background:#9acfea;
padding: 5px;
margin:5px;
}
.active{
background:red;
}
</style>
</head>
<body>
<ul>
{% for i in li %}
{% include 'li.html' %}
{% endfor %}
</ul>
{# {{ page_str|safe }}#}
<div style="float: left;">
<select id='ps' onchange="changePageSize(this);">
<option value="10">10</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
</div>
<div style="float: left;">
{{ page_str }}
</div>
<script src="/static/jquery-1.12.4.min.js"></script>
<script src="/static/jquery-cookie/jquery.cookie.js"></script>
<script>
/*select选项框修改为当前显示数量*/
$(function () {
var v = $.cookie('per_page_count',{'path':"/ug/userlist"});
$('#ps').val(v)
});
/*select选项框选择后自动刷新页面*/
function changePageSize(ths) {
var v = $(ths).val();
$.cookie('per_page_count',v,{'path':"/ug/userlist"});
location.reload();
}
</script>
</body>
</html>
视图函数
from utils import pagination
ulist = []
for i in range(1009):
ulist.append(i)
def userlist(request):
current_page = request.GET.get('p',1)
current_page = int(current_page)
val = request.COOKIES.get('per_page_count',10)
page_obj = pagination.Page(current_page,len(ulist),int(val))
data = ulist[page_obj.start:page_obj.end]
page_str = page_obj.page_str('/ug/userlist/')
return render(request,'userlist.html',{'li':data,'page_str':page_str})
后台模块:pagination
#!/bin/env python
#Author: zhaoyong
from django.utils.safestring import mark_safe
class Page:
'''
实现分页显示功能类
'''
def __init__(self,current_page,data_count,per_page_count = 10,pager_num=7):
'''
用于分页模块
:param current_page: 当前页
:param data_count: 数据总个数
;:param per_page_count: 每页显示数据数量
;:param pager_num: 每页的页码总数
'''
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 all_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.all_count < self.pager_num:
start_page = 1
end_page = self.all_count + 1
else:
if self.current_page < (self.pager_num + 1) / 2:
start_page = 1
end_page = self.pager_num + 1
else:
start_page = self.current_page - (self.pager_num - 1) / 2
end_page = self.current_page + (self.pager_num + 1) / 2
if self.current_page + (self.pager_num - 1) / 2 > self.all_count:
start_page = self.all_count - self.pager_num + 1
end_page = self.all_count + 1 if self.current_page <= 1:
prv = '<a class="page" href="javascript:void(0);">上一页</a>'
else:
prv = '<a class="page" href=%s?p=%s>上一页</a>' % (base_url,self.current_page - 1)
page_list.append(prv)
for i in range(int(start_page), int(end_page)):
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.all_count:
next = '<a class="page" href="javascript:void(0);">下一页</a>'
else:
next = '<a class="page" href=%s?p=%s>下一页</a>' % (base_url,self.current_page + 1)
page_list.append(next)
jump = '''
<input type='text' /><a onclick="jumpto(this,'%s?p=');">GO</a>
<script>
function jumpto(ths,base){
var val = ths.previousSibling.value;
if(val.length != 0){
location.href = base + val;
}
}
</script>
''' % (base_url)
page_list.append(jump)
page_str = mark_safe(''.join(page_list))
return page_str
最新文章
- 基于synchronized 或 ReadWriteLock实现 简单缓存机制
- Module Zero之权限管理
- grub2挂在iso镜像“ /dev/disk/by-label/XXXX error: boot device didn&#39;t show up after 30 seconds”问题
- centos6.5安装node.js
- 如何在VBA窗体中使用 DataGrid 控件?
- Camel In Action 阅读笔记 第一部分概述 + 第一章概述 认识Camel
- 【安全组网】思科IOS设备基础应用
- mongDB基本命令和Java操作MongoDB
- C#删除数组元素代码
- 图论(floyd算法):NOI2007 社交网络
- 【译】typeof null的前世今生
- python基础教程第2章——列表与元组笔记
- getline与get函数的区别
- linux上安装Jmeter
- Struts2中的一个类型转换示例
- tcpdump的表达元
- zoj 3195 Design the city LCA Tarjan
- 【BZOJ2054】疯狂的馒头(并查集)
- GIT结合android studio使用总结
- opencv学习之路(25)、轮廓查找与绘制(四)——正外接矩形