2016-05-07 171 views
1

我想在django rest框架中限制对myweb/api的访问。Django rest框架API许可

我已经试过:

REST_FRAMEWORK = { 
    'DEFAULT_PERMISSION_CLASSES': (
     'rest_framework.permissions.IsAuthenticated', 
    ) 
} 

但是,无论我想要只限制MyWeb即可/ API页面访问

+0

请看本教程https://godjango.com/43-permissions-authentication-django-rest-framework-part-2/ –

+1

您可以为myweb/api下的每个视图指定权限类。这里有两个例子:http://www.django-rest-framework.org/api-guide/permissions/#setting-the-permission-policy –

回答

1

你可以在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文件的默认列表视图。