django 往session写信息

def main(req):
          try:
             req.session['username']
             return render_to_response('main.html')
          except:
             try:
                 a=req.POST['username']
                 if (check_user(req.POST['username'],req.POST['password'])== 1):
                    req.session['username']=req.POST['username']
                    return render_to_response('main.html')
                 else:
                  response = "用户名或密码错误"
                  return HttpResponse(response)
                  #return redirect('/index/')
             except:
               return redirect('/index/')



  req.session['username']=req.POST['username']
  
  其中的 req.session['username']=req.POST['username'] 执行了以下几步:

1.生成随机的sessionID字符串

2.将sessionID和用户的信息在数据库中保存为一个键值对

3.通过cookie将sessionID保存在客户端上

这时候通过用户再次向服务器发送请求时服务器就可以通过请求中的sessionID判断用户的信息了,从而达到保存登录状态的要求。
原文地址:https://www.cnblogs.com/hzcya1995/p/13349136.html