首页 > 代码库 > Django session

Django session

  • Session登陆实例

session存在于客户端,cookies存在于服务器

views:

 

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render,render_to_response,HttpResponse,redirect
from django.contrib import sessions
# 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‘] = {‘username‘:user}#给本次会话者记录下来
            return redirect(‘/app02/index/‘)#重定向到目标页面
        else:
            return render_to_response(‘app02/login.html‘,{‘msg‘:‘用户名或密码错误‘})#前一个参数是模板页面,后一个参数是变量
    return render_to_response(‘app02/login.html‘)
def index(request):
    user_dict = request.session.get(‘is_login‘,None)
    if  user_dict:#如果此时会话存在则可以进入这个页面
        return render_to_response(‘app02/index.html‘,{‘userinfo‘:user_dict[‘username‘]})
    else:#否则重新登陆
        return redirect(‘/app02/login/‘)


def logout(request):
    #删除session
    del request.session[‘is_login‘]
    return redirect(‘/app02/login/‘)

 

具体配置,见:http://www.cnblogs.com/wupeiqi/articles/5246483.html

 

Django session