第一步先在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"})
接口寫完之後,在配置個路由就可以是用了