![](/img/trans.png)
[英]Django-rest-framework api permission AllowAny authentication failed
[英]Django rest framework api permission
我想在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)
當您通過class屬性或裝飾器設置新的權限類時,您將告訴視圖忽略settings.py文件上設置的默認列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.