第一步先在models下边创建表结构:
class NewUser(models.Model):
phone = models.CharField(verbose_name='手机号', max_length=11, unique=True)
email = models.EmailField(verbose_name='邮箱', max_length=32, unique=True)
nick = models.CharField(verbose_name="用户名", max_length=50)
password = models.CharField(verbose_name="密码", max_length=32, null=True, blank=True)
class Meta:
verbose_name='用户表'
verbose_name_plural=verbose_name
db_table='new_user'
def __str__(self):
return self.nick
之后在view视图里边写接口
def register(request):
email = request.POST.get('email')
nick = request.POST.get('nick')
phone = request.POST.get('phone')
password = request.POST.get('password')
password2 = request.POST.get('password2')
if email and nick and phone and password and password2:
if password != password2:
return JsonResponse({"code": -1, 'mas': "两次输入的密码不一致"})
user_email = models.NewUser.objects.filter(email=email)
user_phone = models.NewUser.objects.filter(phone=phone)
if user_email.exists():
return JsonResponse({'code': -1, 'msg': 'email 存在'})
if user_phone.exists():
return JsonResponse({'code': -1, 'msg': 'phone 存在'})
new_password = md5(password)
uesr_save = models.NewUser(email=email, nick=nick, phone=phone, password=new_password)
uesr_save.save()
return JsonResponse({'code': 0, 'msg': 'success'})
else:
return JsonResponse({'code': -1, "msg": "不能为空"})
最后在user里边来加载
以上是注册的接口,下边写登录的接口,并生成token,给生成的token存在redis里边
首先第一步,配置redis:
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
'DECODE_RESPONSES':True #这个的意思是让默认返回字符串
}
},
"user": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
},
}
给这个配置放到settings下
之后使用pip install django_redis俩安装redis模块
在view视图层里边写接口的时候。先导入? import? django_redis就可以用了
这个解决重复登录的方法是,向redis中增加一个key
def login2(request):
username = request.POST.get('username')
password = request.POST.get('password')
if username and password:
user = models.NewUser.objects.filter(Q(email=username) | Q(phone=username)) # 相当于or
if not user.exists():
return JsonResponse({'code': -1, 'msg': '用户名输入错误'})
if user.first().password != md5(password):
return JsonResponse({'code': -1, 'msg': '密码输入错误'})
user_key = 'seeeion_id:%s ' % user.first().phone
res = django_redis.get_redis_connection()
redis_token = res.get(user_key)
print("redis_token",redis_token)
if redis_token:
return JsonResponse({'code': 0, 'msg': '已经登录过了,无需重复登录', "token": redis_token.decode()})#decode()是转成字符串
token = md5(str(time.time()) + username)
user_dict = json.dumps(model_to_dict(user.first()))
expire_time = 60 * 60 # session到期时间
res.set(user_key, token, expire_time)
res.set(token, user_dict, expire_time)
return JsonResponse({'code': 0, 'msg': '登录成功', 'token': token})
else:
return JsonResponse({'code': -1, "msg": "not null"})
接口写完之后,在配置个路由就可以是用了
|