DRF之TokenAuthenticationz认证组件的使用
2020-04-14 本文已影响0人
向日葵1884
daphne报错,很尴尬,查的时候发现另一个方案更符合需求
第一步:注册认证组件并配置
INSTALLED_APPS = [
...
'rest_framework',
'rest_framework.authtoken',
...
]
REST_FRAMEWORK = {
...
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
)
...
}
注意:在settings.py中添加这个app后,它会帮我们在数据库中生成一张authtoken表,所以我们要确保manage.py migrate在更改设置后运行。
第二步:设计登录和登出的URL
from django.urls import path
urlpatterns = [
path('login', LoginView.as_view()),
path('logout', LogoutView.as_view()),
]
第三步:views类的编写
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from rest_framework.views import APIView
class LoginView(ObtainAuthToken):
def post(self, request, *args, **kwargs):
# 自定义返回结果的格式
ret = BaseResponse.BaseResponse()
# 从request中获取数据, 数据格式必须为 {"username":"用户名","password":"密码"}
serializer = self.serializer_class(data=request.data, context={'request': request})
if serializer.is_valid():
# 获取user对象
user = serializer.validated_data['user']
# 每次用户登录时先删除Token再重新生成Token
Token.objects.filter(user=user).delete()
# 生成新的Token
token, created = Token.objects.get_or_create(user=user)
# 自定义返回内容
ret.msg = "登录成功!"
ser_obj = UserProfileSerializer(user) # 编写好User对象的序列化器
ret.data = ser_obj.data
ret.token = token.key
else:
# 登录失败时返回的内容
ret.code = 1013
ret.msg = "登录失败!用户名或密码错!"
return Response(ret.dict)
class LogoutView(APIView):
queryset = UserProfile.objects.all()
def get(self, request):
ret = BaseResponse.BaseResponse()
try:
# 退出时删除用户登录时生成的Token
Token.objects.filter(user=request.user).delete()
ret.msg = "退出成功!"
except Exception as e:
ret.code = 1013
ret.msg = str(e)
return Response(ret.dict)
- BaseResponse类的代码示例
class BaseResponse(object):
def __init__(self):
self.code = 1000
self.msg = ""
self.data = None
self.token = ""
@property
def dict(self):
return self.__dict__
image