使用令牌

讓我們建立一個需要這種身份驗證機制的新檢視。

我們需要新增這些匯入行:

from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated

然後在相同的 views.py 檔案中建立新檢視

class AuthView(APIView):
    """
    Authentication is needed for this methods
    """
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsAuthenticated,)
 
    def get(self, request, format=None):
        return Response({'detail': "I suppose you are authenticated"})

正如我們在上一篇文章中所做的那樣,我們需要告訴我們的專案我們在 test_app/urls.py 上有一個新的 REST 路徑監聽

from rest_framework.urlpatterns import format_suffix_patterns
from test_app import views
 
urlpatterns = patterns('test_app.views',
    url(r'^', views.TestView.as_view(), name='test-view'),
    url(r'^auth/', views.AuthView.as_view(), name='auth-view'),
)
 
urlpatterns = format_suffix_patterns(urlpatterns)