我想限制 Django Rest 框架中对 myweb/api 的访问。
我已经尝试过:
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
但它限制了所有请求,但我只想限制对 myweb/api 页面的访问。
您可以在settings.py文件中添加自由权限,并在特定的api视图中添加更多限制性权限。
在settings.py中,添加类似以下内容:
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
),
您也可以使用
AllowAny
权限。
您可以使用基于 APIView 类的视图在每个视图或每个视图集的基础上设置身份验证策略。
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
class ExampleView(APIView):
permission_classes = (IsAuthenticated,)
def get(self, request, format=None):
content = {
'status': 'request was permitted'
}
return Response(content)
或者,如果您将 @api_view 装饰器与基于函数的视图一起使用。
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
@api_view('GET')
@permission_classes((IsAuthenticated, ))
def example_view(request, format=None):
content = {
'status': 'request was permitted'
}
return Response(content)
当您通过类属性或装饰器设置新的权限类时,您是在告诉视图忽略在 settings.py 文件中设置的默认列表。