欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 新车 > 快速入手-基于Django-rest-framework的自身组件权限认证(九)

快速入手-基于Django-rest-framework的自身组件权限认证(九)

2025/4/3 5:06:32 来源:https://blog.csdn.net/zsb706496992/article/details/146601083  浏览:    关键词:快速入手-基于Django-rest-framework的自身组件权限认证(九)

1、在对应的视图函数里增加认证(局部起作用,不全局生效)

导入类:

from rest_framework.authentication import (
    BasicAuthentication,
    SessionAuthentication,
)
from rest_framework.permissions import IsAuthenticated, AllowAny

2、基于第八节内容增加以下权限设置内容

#定义认证类型

authentication_classes = [SessionAuthentication]

#定义权限限制

permission_classes = [IsAuthenticated]

备注说明:

AllowAny  允许所有用户,默认权限

IsAuthenticated  仅通过登录认证的用户

IsAdminUser 仅管理员用户

IsAuthenticatedOrReadOnly  已经登录认证的用户可以对数据进行CRUD操作,

                                                  没有登录认证的用户,只能查看数据

3、完整code

from django.shortcuts import render, HttpResponse
from rest_framework.response import Response
from rest_framework.decorators import actionfrom rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import (ListModelMixin,CreateModelMixin,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin,
)
from rest_framework.viewsets import ModelViewSet
from rest_framework import serializersfrom rest_framework.authentication import (BasicAuthentication,SessionAuthentication,
)
from rest_framework.permissions import IsAuthenticated, AllowAnyfrom .models import *
from api.serializer import *# 这种写法实现所有的增删改查,不能够单独进行操作
# class Linkapi(ModelViewSet):
# 不仅可以实现所有的增删改查,而且可以单独也可以全部包含增删改查
class Linkapi(GenericViewSet,ListModelMixin,CreateModelMixin,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin,
):queryset = Link.objects.all()serializer_class = LinkSerializerauthentication_classes = [SessionAuthentication]permission_classes = [IsAuthenticated]# 在原有的二级路由中自定义添加三级路由路径# 访问路径/api/linkapi/{pk}/login/@action(methods=["get", "POST"],detail=True,url_path="login",)def login(self, request, pk):queryset = self.get_queryset()serializer = self.get_serializer(queryset, many=True)return Response(serializer.data)# detail为false表示路径名格式应该为/api/linkapi/get_new_5/@action(methods=["get",],detail=False,)def get_new_2(self, request):obj = Link.objects.all().filter()[:2]serializer = self.get_serializer(instance=obj, many=True)return Response(serializer.data)

4、测试

5、仅允许查询,其他方式请求未授权不能访问

导入包

from rest_framework.permissions import (

    IsAuthenticated,

    AllowAny,

    IsAuthenticatedOrReadOnly,

)

修改视图类内容

# IsAuthenticated 授权登录后可以访问

# IsAuthenticatedOrReadOnly  只允许查询

permission_classes = [IsAuthenticatedOrReadOnly]

6、 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词