修改权限、用户认证方式

  • 在settings中全局配置
1
2
3
4
5
6
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
]
}
  • 基于每个视图集进行配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

class ExampleView(APIView):
authentication_classes = [SessionAuthentication, BasicAuthentication]
permission_classes = [IsAuthenticated]

def get(self, request, format=None):
content = {
'user': unicode(request.user), # `django.contrib.auth.User` instance.
'auth': unicode(request.auth), # None
}
return Response(content)
  • 配合@api_view装饰器基于函数一起使用
1
2
3
4
5
6
7
8
9
10
11
12
from rest_framework.decorators import permission_classes, authentication_classes
class ExampleView(APIView):

@api_view(['GET'])
@authentication_classes([SessionAuthentication, BasicAuthentication])
@permission_classes([IsAuthenticated])
def example_view(request, format=None):
content = {
'user': unicode(request.user), # `django.contrib.auth.User` instance.
'auth': unicode(request.auth), # None
}
return Response(content)
  • 配合@action装饰器基于函数一起使用
1
2
3
4
5
6
7
8
9
10

class ExampleView(APIView):

@action(methods=['get'], detail=False, url_path='url', url_name='url', permission_classes=(IsAuthenticated,), authentication_classes=(SessionAuthentication, BasicAuthentication))
def example_view(request, format=None):
content = {
'user': unicode(request.user), # `django.contrib.auth.User` instance.
'auth': unicode(request.auth), # None
}
return Response(content)

参考链接:django-rest-framework