Django之cookie和session
cookie
history = request.COOKIES.get('history',None) cookie_str = '' if history: cookies = history.split(',') if kw in cookies: cookies.remove(kw) cookies.insert(0,kw) # 如果存储个数大于5 if len(cookies) >5: # 去掉最后一个 cookies.pop() cookie_str = ','.join(cookies) else: cookies = [] # 将本次搜索关键词放入cookies中 cookie_str = kw response = render(request,'result.html',{'historys':cookies,'hot_top5':hot_top5}) response.set_cookie('history',cookie_str) return response
session
def mylogin(request): if request.method == 'GET': # 从cookie中取出保存的u_name u_name =request.COOKIES.get('u_name','') return render(request,'login.html',{'u_name':u_name}) elif request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') if username == 'admin' and password == 'admin123': # 判断有没有登陆之前访问的地址 if request.COOKIES.get('next_url'): # 重定向到登录之前的地址 response = redirect(request.COOKIES.get('next_url')) else: # 重定向到主页 response = redirect('/') checkbox = request.POST.get('checkbox',None) # 在用户名和密码正确的情况下,判断是否记住账户 # 如果记住账户,需要将用户的名放入cookies中,下次访问登录界面时,就可以直接从cookie中读取用户保留的信息 if checkbox: response.set_cookie('u_name',username) else: response.set_cookie('u_name','') # 用户登录成功,将用户信息保存到session中 request.session['u_name'] = username return response