您可以像任何其他 Django 应用程序一样设置 url,documented here
# urls.py
from django.conf.urls import url
from somewhere import SnippetList
urlpatterns = [
url(r'^your/url/$', SnippetList.as_view()),
]
关于 DRY 与您的方法,您可以定义您想要响应的方法,并调用 getWorstStudents(顺便说一句,我将其称为 get_worst_students)。假设您要响应 post 方法:
# views.py
from rest_framework.response import Response
def getWorstStudents(params)
class SnippetList(APIView):
def post(self, request, *args, **kwargs):
# call getWorstStudents method here and response a Response Object
您可以在SnippetList 类或其他文件中定义getWorstStudents,以便在需要的地方导入。
最后,关于身份验证,DRF 为此提供了类,documented here。
从文档中,您需要在 settings.py 文件中定义它:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
)
}
并在您的视图中使用它:
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
class ExampleView(APIView):
authentication_classes = (SessionAuthentication, BasicAuthentication)
permission_classes = (IsAuthenticated,)
def get(self, request, format=None):
content = {
'user': unicode(request.user), # `django.contrib.auth.User` instance.
'auth': unicode(request.auth), # None
}
return Response(content)
您还可以定义自己的身份验证类并将其设置在authentication_classes 元组中。 Custom authentication classes documented here.