Django缓存分为Session和Cookie:Session为放在服务器端的缓存;Cookie为放在客户端(浏览器)的缓存。
Session一般用来保存登录会话;Cookie一般用来保存一些个性化的设置。
Session示例:
#!/usr/bin/env python #-*- encoding:utf-8 -*- from django.shortcuts import render,redirect # Create your views here. def login(request): if request.method == 'POST': user = request.POST.get('username',None) pwd = request.POST.get('password',None) if user == 'alex' and pwd == '123': #登录成功 request.session['is_login'] = {'user':user} #设置session,表示用户登录成功 return redirect('/login/index/') else: #登录失败 return render(request,'login/login.html',{'msg':'用户名或密码错误'}) return render(request,'login/login.html') def index(request): user_dict = request.session.get('is_login',None) #获取session,用于判断用户是否登录成功 if user_dict: return render(request, 'login/index.html',{'username':user_dict['user']}) else: return redirect('/login/login') def logout(request): del request.session['is_login'] #删除session return redirect('/login/login')
Cookie示例:
def Page(request,page): #第二种分页方式 counts = Host.objects.all().count() # 获取数据总条数 #print request.POST per_item = request.COOKIES.get('pager_num',5) #从cookie中获取key为pager_num的值,获取不到则设置默认值为5 per_item = int(per_item) #print 'per_item:',per_item pages = PageInfo(page,counts,'/web/page/',per_item) result = Host.objects.all()[pages.start_page:pages.end_page] # 获取第page页内容 page_string = pages.page_string #print 'page_string:',page_string ctx = { 'data':result, 'count':counts, 'page_string':page_string, } response = render(request,'page.html',ctx) #response.set_cookie(key='k1',value='v1') #设置cookie #request.COOKIES #获取cookie return response
关注我的公众号,不定期推送资讯
本文来自博客园,作者:链条君,转载请注明原文链接:https://www.cnblogs.com/MacoLee/p/5841693.html