- views:请求的其他信息
- 模板继承和引用
- 自定义函数(simple_tag & filter)
- 分页示例
- cookie
- CBV和FBV用户认证装饰器
1.views-请求的其他信息
1 from django.core.handlers.wsgi import WSGIRequest2 3 request.environ4 request.environ['HTTP_USER_AGENT']
2.模板继承和引用
1 urlpatterns = [2 #path('admin/', admin.site.urls),3 url(r'tp11',views.tp11),4 url(r'tp12',views.tp11),5 url(r'tp13',views.tp11),6 7 ]
1 def tp11(request): 2 3 user_list = [1,2,3,] 4 5 return render(request,'tp11.html',{ 'u':user_list}) 6 7 8 def tp12(request): 9 name = 'root'10 11 return render(request, 'tp12.html', { 'name': name})12 13 14 def tp13(request):15 status = '已删除'16 17 return render(request, 'tp13.html', { 'status': status})
1 2 3 4 5{% block title%} {% endblock %} 6 7 14 {% block css %} {% endblock %}15 16潇韩海17 18 {% block content %} {% endblock %}19 20 21 {% block js %} {% endblock %}22 23
1 {% extends 'master.html'%} 2 3 {% block title %} 用户管理 {% endblock %} 4 5 {% block content %} 6
- 7 {% for i in u %} 8
- { { i }} 9 {% endfor %}10
1
3.自定义函数(simple_tag & filter)
simple_taga. app创建templatetags目录b. 任意xxoo.py文件c.创建template对象reqisterd. @register.simple_tag def func(a1,a2) return "asasd" e.settings中注册APP f. 顶部{% load xxoo %} g. {% 函数名 arg1 arg2%} 缺点: 参数任意
1 url(r'tp14/',views.tp14),
1 __author__ = 'Administrator' 2 from django import template 3 from django.utils.safestring import mark_safe 4 5 register = template.Library() 6 7 @register.simple_tag 8 def houyafan(a1,a2,): 9 return a1 + a210 11 @register.filter12 def jiajingze(a1,a2):13 return a1 + str(a2)
1 {% load xxoo %} 2 3 4 5 67 8 9 { { name }}10 { { name|lower }}11 { { name|truncatechars:"3" }}12 13 {% houyafan 2 8 %}14 15 { { "maliya"|jiajingze:"LS,YH" }}16 17 {% if "maliya"|jiajingze:"LS,YH" %}18 {% endif %}19 20 21 22
4.分页示例
1 url(r'user_list/',views. user_list),
1 LISI = [] 2 for i in range(109): 3 LISI.append(i) 4 5 def user_list(request): 6 current_page = request.GET.get('p',1) 7 current_page = int(current_page) 8 start = (current_page-1) * 10 9 end = current_page * 1010 data = LISI[start:end]11 12 all_count = len(LISI)13 count,y = divmod(all_count,10)14 if y:15 count += 116 17 page_list = []18 for i in range(1,count+1):19 if i == current_page:20 temp = '%s' %(i,i)21 else:22 temp = '%s' %(i,i)23 24 page_list.append(temp)25 page_str = mark_safe("".join(page_list))26 return render(request,'user_list.html', { 'li':data,'page_str':page_str})
1 2 3 4 5Title 6 18 19 20
- 21 {% for item in li %}22 {% include 'li.html' %}23 {% endfor %}24
26 { { page_str }}27
28 29 1
分页优化版
1 from django.shortcuts import render 2 from django.utils.safestring import mark_safe 3 from utils import pagination 4 LISI = [] 5 for i in range(500): 6 LISI.append(i) 7 8 def user_list(request): 9 current_page = request.GET.get('p',1)10 current_page = int(current_page)11 12 val = request.COOKIES.get('per_page_count',10)13 val = int(val)14 15 page_obj = pagination.Page(current_page,len(LISI),val)16 17 data = LISI[page_obj.start:page_obj.end]18 19 page_str = page_obj.page_str("/user_list")20 21 return render(request,'user_list.html', { 'li':data,'page_str': page_str})22 23 ###############################################################################24 from utils import pagination25 26 LIST = []27 for i in range(500):28 LIST.append(i)29 30 def user_list(request):31 current_page = request.GET.get('p', 1)32 current_page = int(current_page)33 34 val = request.COOKIES.get('per_page_count')35 val = int(val)36 page_obj = pagination.Page(current_page,len(LIST),val)37 data = LIST[page_obj.start:page_obj.end]38 39 page_str = page_obj.page_str("/user_list/")40 41 return render(request,'user_list.html', { 'li': data,'page_str': page_str})
1 __author__ = 'wei.han' 2 from django.utils.safestring import mark_safe 3 4 5 class Page: 6 def __init__(self, current_page, data_count, per_page_count=10, pager_num=7): 7 #用户点击值 8 self.current_page = current_page 9 #数据总数10 self.data_count = data_count11 #每页显示10条数据12 self.per_page_count = per_page_count13 #7页14 self.pager_num = pager_num15 16 #开始(显示居中)17 @property18 def start(self):19 return (self.current_page - 1) * self.per_page_count20 21 # 结束(显示居中)22 @property23 def end(self):24 return self.current_page * self.per_page_count25 26 #总页数27 @property28 def total_count(self):29 v, y = divmod(self.data_count, self.per_page_count)30 if y:31 v += 132 return v33 34 #url35 def page_str(self, base_url):36 page_list = []37 38 if self.total_count < self.pager_num:39 start_index = 140 end_index = self.total_count + 141 else:42 if self.current_page <= (self.pager_num + 1) / 2:43 start_index = 144 end_index = self.pager_num + 145 else:46 start_index = self.current_page - (self.pager_num - 1) / 247 end_index = self.current_page + (self.pager_num + 1) / 248 if (self.current_page + (self.pager_num - 1) / 2) > self.total_count:49 end_index = self.total_count + 150 start_index = self.total_count - self.pager_num + 151 52 if self.current_page == 1:53 prev = '上一页'54 else:55 prev = '上一页' % (base_url, self.current_page - 1,)56 page_list.append(prev)57 58 for i in range(int(start_index), int(end_index)):59 if i == self.current_page:60 temp = '%s' % (base_url, i, i)61 else:62 temp = '%s' % (base_url, i, i)63 page_list.append(temp)64 65 if self.current_page == self.total_count:66 nex = '下一页'67 else:68 nex = '下一页' % (base_url, self.current_page + 1,)69 page_list.append(nex)70 71 jump = """72 GO73 79 """ % (base_url,)80 81 page_list.append(jump)82 83 page_str = mark_safe("".join(page_list))84 85 return page_str
1 2 3 4 56 18 19 20
- 21 {% for item in li %}22 {% include 'li.html' %}23 {% endfor %}24
27 33
34 35 36 { { page_str }}37
38 39 40 41 56 57 5.cookie
rep = HttpResponse(...) 或 rep = render(request, ...) rep.set_cookie(key,value,...)rep.set_signed_cookie(key,value,salt='加密盐',...) 参数: 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获取(不是绝对,底层抓包可以获取到也可以
设置cookie有限时间
request.COOKIES.get('username111')reqpone = render(request,'index.html')设置cookie,关闭浏览器后就失效response.set_cookie('key','value')设置cookie,10秒后失效response.set_cookie('username111','value',max_age=10)return response设置cookie,5秒后失效import datetimecurrent_date = datetime.datetime.utcnow()current_date = current_date + datetime.timedelta(seconds=5)res.set_cookie('username111',u,expires=current_date)
cookie加密
#request.COOKIES.get('...')#request.set_cookie(...)obj = HttpResponse('s')加密obj.set_signed_cookie('username','kanbazi',salt='jiamizifuchuan')获取加密request.get_signed_cookie('username',salt="jiamizifuchuan")return response
6.CBV和FBV用户认证装饰器
FBV
1 url(r'index/',views.index),
1 from django.shortcuts import render,redirect 2 from django.utils.safestring import mark_safe 3 4 user_info = { 5 'dachengzi': { 'pwd': "123"}, 6 'kanbazi': { 'pwd': "123"}, 7 } 8 9 10 def login(request):11 if request.method == "GET":12 return render(request, 'login.html')13 if request.method == "POST":14 u = request.POST.get('username')15 p = request.POST.get('pwd')16 dic = user_info.get(u)17 if not dic:18 return render(request,'login.html')19 if dic['pwd'] == p:20 res = redirect('/index/')21 res.set_cookie('username111',u)22 return res23 else:24 return render(request,'login.html')25 26 27 def auth(func):28 def inner(request,*arges,**kwargs):29 v = request.COOKIES.get('username111')30 if not v:31 return redirect('/login/')32 return func(request,*arges,**kwargs)33 return inner34 35 36 @auth37 def index(request):38 v = request.COOKIES.get('username111')39 return render(request,'index.html',{ 'current_user': v})
CBV
1 from django import views 2 from django.utils.decorators import method_decorator 3 4 @method_decorator(auth,name='dispatch') 5 class Order(views.View): 6 7 # @method_decorator(auth) 8 # def dispatch(self,request, *args,**kwargs): 9 # return super(Order,self).dispatch(request, *args, **kwargs)10 11 # @method_decorator(auth)12 def get(self,request):13 v = request.COOKIES.get('username111')14 return render(request,'index.html',{ 'current_user': v})15 16 def post(self,request):17 v = request.COOKIES.get('username111')18 return render(request,'index.html',{ 'current_user': v})
1 2 3 4 513 14Title 6 7 8
1 2 3 4 5Title 6 7 8欢迎登录:{ { current_user }}
9 10