1. 自定义认证类
1.1 view
from api import models
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
class PublicAuthentication(BaseAuthentication):
"""普通校验,记录登录的用户"""
def authenticate(self, request):
# 请求头取数据,都是HTTP_大写(在django)
token = request.META.get('HTTP_AUTHORIZATION')
# 在认证组件中,如果返回一个None,是交给下一个组件处理
if not token:
return None
user_obj = models.UserInfo.objects.filter(token=token).first()
if not user_obj:
return None
return (user_obj, token) # request.user/auth
class LoginAuthentication(BaseAuthentication):
"""必须登录认证"""
def authenticate(self, request):
# 请求头取数据,都是HTTP_大写(在django)
token = request.META.get('HTTP_AUTHORIZATION')
# 在认证组件中,如果返回一个None,是交给下一个组件处理
if not token:
raise AuthenticationFailed() # 前端返回403
user_obj = models.UserInfo.objects.filter(token=token).first()
if not user_obj:
raise AuthenticationFailed()
return (user_obj, token) # request.user/auth
1.2 settings
# rest_framework配置(全局)
REST_FRAMEWORK = {
'UNAUTHENTICATED_USER': None,
'UNAUTHENTICATED_TOKEN': None,
'DEFAULT_AUTHENTICATION_CLASSES': [
'utils.auth.PublicAuthentication'
],
}
2. 同一个类中get/post使用两个不同的认证类
该类视图需要重写get_authenticators
from utils.auth import LoginAuthentication, PublicAuthentication
class CommentAPIView(APIView):
"""获取更多评论&保存数据"""
def get_authenticators(self):
# 重写认证类
if self.request.method == 'POST':
return [LoginAuthentication(), ]
return [PublicAuthentication(), ]
def get(self, request, *args, **kwargs):
"""获取更多评论,通过root"""
print(request.user)
root = int(request.query_params.get('root'))
# print(root)
queryset = models.Comment.objects.filter(root=root)
# print(queryset)
ser = CommentModelSerializer(instance=queryset, many=True)
return Response(data=ser.data)
def post(self, request, *args, **kwargs):
"""保存评论数据"""
ser = PostCommentModelSerializer(data=request.data) # ...
# print(request.data)
if ser.is_valid():
ser.save(userinfo_id=1)
# 评论数+1
new_id = ser.validated_data.get('new').id
models.Release.objects.filter(id=new_id).update(release_num=F('release_num') + 1)
return Response(ser.data, status=status.HTTP_201_CREATED)
return Response(ser.errors, status=status.HTTP_400_BAD_REQUEST)