1.思路
2.程序实现
1.用户系统类
这里模拟一个蹩脚的用户系统类(userSystem),如下:
#coding=utf-8
#Redis实现用户系统 __author__ = 'beginman' import redis import datetime import hashlib r = redis.StrictRedis(host='localhost', port='6379', db=0) class usSystem(object): def __init__(self, request,response=None, uid=0, **kwargs): self.request = request self.response = response self.kwargs = kwargs self.uid = uid # user id self.sessionid = None def testCookie(self): """事先在登陆方法中下了request.session.set_test_cookie()的套子""" if self.request.session.test_cookie_worked(): self.request.session.delete_test_cookie() return True return False def getUsObj(self): """返回用户对象,有则说明用户已登陆,无则注销""" self.sessionid = self.request.COOKIES.get('sessionid', None) if r.exists(self.sessionid): if r.exists('sessionid_%s' %self.sessionid): return r.hget('sessionid_%s' %self.sessionid, 'uid') return None def setCookieAndSession(self): """cookie在登陆成功后已经写入""" self.sessionid = self.request.COOKIES.get('sessionid', None) if not self.sessionid: # set cookie h = hashlib.md5() h.update(datetime.datetime.now()) self.response.set_cookie('sessionid', h.hexdigest()) self.sessionid = h.hexdigest() if not r.exists('sessionid_%s' %self.sessionid): #set session r.hset('sessionid_%s' %self.sessionid,'uid', self.uid) return True
然后在登陆方法中这样写:
# coding=utf-8
__author__ = 'beginman' from django.shortcuts import render from django.http import HttpResponseRedirect from form import LoginForm from common.userSystem import usSystem import redis import datetime r = redis.StrictRedis(host='localhost', port='6379', db=0) def home(request): return render(request, 'index.html') def usLogin(request): context = {} if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): us = form.cleaned_data['us'] pwd = form.cleaned_data['pwd'] if r.exists('us:%s:id' %us): # 检查是否存在该用户关系键值 uid = r.get('us:%s:id' %us) # 获取该用户在user表中对应的id if r.exists('user:%s' %uid): # 检查是否存在该用户键值(如user:1) us_, pwd_ = r.hmget('user:%s' %uid, 'username', 'pwd') # 获取该用户的用户名密码 if us_ == us and pwd_ == pwd: # 校验成功 r.hincrby('user:%s' %uid, 'login_count', 1) # 登陆次数累加 r.hset('user:%s' %uid, 'last_login_date', datetime.datetime.now()) # 添加最近登陆 # set Cookies res = HttpResponseRedirect('/') ussys = usSystem(request, res, uid) if ussys.testCookie() and ussys.setCookieAndSession(): return res context['msg'] = u'账号或密码错误' context['form'] = form request.session.set_test_cookie() form = LoginForm() context['form'] = form return render(request, 'login.html', context)
同时要注意中间件处理:
#coding=utf-8
#中间件扩展 __author__ = 'beginman' from django.http import HttpResponseRedirect from django.conf import settings from common.userSystem import usSystem class Mymiddleware(object): def process_request(self, request): """Request预处理函数""" path = str(request.path) request.session['domain'] = settings.DOMAIN if path.startswith('/site_media/'): return None #验证登陆 ussys = usSystem(request) if ussys.getUsObj(): pass
在一些需要登陆后才能访问的可以写在验证登陆后面.这里还需要慢慢改进.