django操作redis 登录验证token

1.settings里配置

增加一个字典(里面配置redis信息)

 

2.安装django_redis模块,并导入 from django_redis import get_redis_connection

r = get_redis_connection()# 实例一个链接对象r 方法里面传settings里配置的 redis名字,不传默认是default

r.set()存入redis

3.思路

  登录时首先校验用户名密码,然后产生token存入 redis并且设置失效时间,具体代码如下

models.py (生成user表)

class User(BaseModel):
    username = models.CharField(verbose_name='用户名',max_length=50,unique=True)
    password = models.CharField(verbose_name='密码',max_length=50)

    def __str__(self):
        return self.username

    class Meta:
        db_table = 'user'

项目中的utils.py方法,生成token和验证token的方法

import itsdangerous #使用itsdangerous生成临时身份令牌
from django.conf import settings
settings.SECRET_KEY #settings下的secret_key
from .const import token_expire
class Token:
    tjss = itsdangerous.TimedJSONWebSignatureSerializer(settings.SECRET_KEY, expires_in=token_expire)

    @classmethod#定义为类方法,产生token
    def create_token(cls,data):
        token = cls.tjss.dumps(data).decode()
        return token

    @classmethod#验证token
    def check_token(cls,token):
        try:
            data = cls.tjss.loads(token)
        except:
            return False
        return data

forms.py中 写验证用户名密码的逻辑

class UserForm(forms.Form,FormatErrMsg):
    username = forms.CharField(max_length=50,min_length=4)
    password = forms.CharField(max_length=50,min_length=6)

    def clean(self):
        '''登录校验 查询数据库存的用户密码并且将查询到的添加到cleaned_data里'''
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        u = models.User.objects.filter(username=username,password=password).first()
        if u:
            self.cleaned_data['u'] = u 
            print(self.cleaned_data)
        else:
            raise forms.ValidationError('账号/密码错误')

view.py中写产生token的代码,存入redis里,并设置超时时间

class LoginView(View):
    def get(self,request):
        form = UserForm(request.GET)
        if form.is_valid():
            user_id = form.cleaned_data.get('u').id
            user_name = form.cleaned_data.get('u').username
            data = {'id':user_id,'username':user_name}
            token = Token.create_token(data)
            r = get_redis_connection()
            key = session_pre + user_name
            r.set(key,token,token_expire)
            return custom_response.NbResponse(token=token)
        else:
            return custom_response.NbResponse(-1,form.error_msg)

其中const.py中定义了两个常量

token_expire = 60*60*1 #设置tonke有效期为1小时

session_pre = 'session:'

 

posted @ 2020-01-29 18:07  小马哥007  阅读(1280)  评论(0编辑  收藏  举报