使用令牌

让我们创建一个需要这种身份验证机制的新视图。

我们需要添加这些导入行:

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)