这篇记录的是restframework的登录,权限配置,本质是在django模块的基础上的封装,以减少我们的代码量。django底层详见上篇django auth permission
restframework 自带的用户登录模块
urls.py
from django.urls import path,include urlpatterns = [ path(r'api-auth/', include('rest_framework.urls', namespace='rest_framework')), ]
permission
查看源码,restframework现成的类有7个,介绍如下常用四个
AllowAny:允许无限制访问
IsAuthenticated :允许访问任何经过身份验证的用户,并拒绝访问任何未经身份验证的用户
IsAdminUser:允许超级用户访问
IsAuthenticatedOrReadOnly:对经过身份验证的用户的允许完全访问,但对未经身份验证的用户的允许只读访问
@six.add_metaclass(BasePermissionMetaclass) class BasePermission(object): """ A base class from which all permission classes should inherit. """ def has_permission(self, request, view): """ Return `True` if permission is granted, `False` otherwise. """ return True def has_object_permission(self, request, view, obj): """ Return `True` if permission is granted, `False` otherwise. """ return True
但完全可以我们自己来写,仅需要面向上述源码任意一个接口即可。
utils/permission.py
扫描二维码关注公众号,回复:
5519683 查看本文章
from rest_framework.permissions import BasePermission class IsLoginReadOnly(BasePermission): """ 自定义权限设置 """ def has_permission(self,request,view): return all((request.user.is_authenticated,request.user.is_staff))
如果你需要测试请求是读取操作还是写入操作,则应该根据常量SAFE_METHODS
检查请求方法,SAFE_METHODS
是包含'GET'
, 'OPTIONS'
和'HEAD'
的元组
if request.method in permissions.SAFE_METHODS: # 检查只读请求的权限 else: # 检查读取请求的权限
views.py
from rest_framework import mixins from rest_framework import viewsets from .models import UserProfile from .serializers import UserProfileSerializer from utils.permission import IsAuthenticatedOrReadOnly class UsersListViewSets(viewsets.GenericViewSet,mixins.ListModelMixin): """ 用户列表 """ queryset = UserProfile.objects.all() serializer_class = UserProfileSerializer permission_classes = (IsAuthenticatedOrReadOnly,)