本博客作为个人笔记使用 主要是 记录 APIView 类的 用户认证 权限校验 以及 节流的使用与一些 原理说明 水平十分有限
创建 用户 使用的是django自带的User。
序列化器 如下
from django.contrib.auth.models import User
from rest_framework import serializers
class MyUserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'username', 'password', 'email']
如果不会用序列化器可以参考https://blog.csdn.net/dandanfengyun/article/details/84779459
所使用的 包
import uuid
from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from django.core.cache import caches
from django.shortcuts import render
from rest_framework import status
from rest_framework.generics import ListCreateAPIView, ListAPIView
from rest_framework.response import Response
cache = caches['user'] # 缓存
使用一个视图类完成 User 创建 主要是 密码的设置
class RegisterAPI(ListCreateAPIView):
serializer_class = MyUserSerializer
def list(self, request, *args, **kwargs):
res = {
'code': 0,
'msg': '注册界面',
}
return Response(res)
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
user = User.objects.get(pk=serializer.data.get('id'))
user.set_password(user.password)
user.save()
new_serializer = self.get_serializer(user)
return Response(new_serializer.data, status=status.HTTP_201_CREATED, headers=headers)
User 类自带的方法 self.set_password()可以将设置保护密码
在 url 路由中 加入该视图函数
url(r'^register$', RegisterAPI.as_view()),
前端代码未写 可以直接使用 Postman 工具发起请求
图为注册成功 返回的 数据
登录 逻辑 则是 当用户登录时 验证通过后 生成一个 随机 token 值 可用 UUID生成。然后将token 值 作为 key 登录用户 id 作为value 保存在 缓存中,缓存可以设置过期时间 。然后将token值 返回给客户端。 当某个视图需要用户为登录状态才能访问时 。客户发起的请求中应该 带有 token 值。可以设置为请求附带的参数 ?token=‘asghjfugyig’ 之类。 如果根据该token可以在缓存中查找到 用户id 且根据该id能找到对应user. 则为 登录状态。 可以访问 , 否则 不可以访问。
这里 需要用到 缓存 可以使用 redis 缓存 。
setting 中设置
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
},
"user": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/10",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
}
}
# 用户登录缓存时间
USER_ALIVE = 60*60*24*15 # 15天
登录的视图类
class LoginAPI(ListAPIView):
def list(self, request, *args, **kwargs):
username = request.data.get('username')
password = request.data.get('password')
user_login = authenticate(username=username, password=password) # User自带的验证 返回值 为user
if user_login:
token = request.query_params.get('token', None)
user_id = cache.get(token, None)
if not user_id:
user_cache = User.objects.filter(pk=user_id).first()
if not (user_cache is user_login):
# 当前 缓存中 没有保存 用户
token = uuid.uuid4().hex
# 设置 token 到 缓存中
cache.set(token, user_login.id, settings.USER_ALIVE)
res = {
'code': 0,
'msg': '登陆成功',
'username': user_login.username,
'token': token,
}
else:
res = {
'code': 1,
'msg': '登