码迷,mamicode.com
首页 > 其他好文 > 详细

Django缓存设置

时间:2016-09-05 12:23:14      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

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

 

Django缓存设置

标签:

原文地址:http://www.cnblogs.com/MacoLee/p/5841693.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!