利用cookie保存用户登录信息初步

设置cookie

response对象.set_cookie('key','value',多少秒后过期)

获取cookie

request对象.COOKIES.get('key')

1.我们继续前一篇的代码

def hi(request):
    msg = {'result':''}

    loginSuccess = False # 是否登录成功标识

    if user.userLogin(request.POST.get('username'),request.POST.get('pwd')):
        loginSuccess = True
        msg['result'] = '登录成功'
    elif request.COOKIES.get('userlogin_username') != None :
        msg['result'] = '已经登录,当前用户是:' + request.COOKIES.get('userlogin_username')
    else:
        msg['result'] = '登录失败'

    myReponse = render_to_response("index.html",msg)

    # 如果登录成功,则设置cookies
    if loginSuccess:
        myReponse.set_cookie('userlogin_username',request.POST.get('username'),3600)

    return myReponse

hi()方法接收了一个request对象;最后返回一个response对象(该对象由render_to_response函数生成)

你可能感兴趣的:(python,web实战基础)