我对 python 世界非常陌生,现在我使用 Django 1.8 和 Rest Framework 构建一个应用程序,我想创建一个类 View 来干燥我的代码。
例如,我想为我的系统中的学生提供类(class) View
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
class SnippetList(APIView):
def getWorstStudents(self, request, format=None):
# Logic here
如何在 urls.py 中分配指定的 URL 来调用此方法?
而且我还实现了REST框架JWT Auth http://getblimp.github.io/django-rest-framework-jwt/用于 token 身份验证。
如何限制访问以仅允许经过身份验证的用户访问此网址?
提前谢谢您!
最佳答案
首先,从 ModelViewSet
而不是 APIView
子类化您的 View 。其次,在 getWorstStudents
方法中使用 @list_route
装饰器。第三,用路由器将 urls.py
中的所有内容绑定(bind)起来。
它应该看起来像(我没有测试代码):
views.py
class StudentsViewSet(viewsets.ViewSet):
@list_route(methods=['get'], permission_classes=(IsAuthenticated,)) # you can define who can access this view here
def getWorstStudents(self, request, format=None):
# Logic here
# routers.py
router = routers.DefaultRouter()
router.register(r'students', views.StudentsViewSet, base_name='student')
# urls.py
import .routers import router
urlpatterns = [
url(r'^', include(router.urls)),
]
路由器将生成一个名为 student-getWorstStudents
的 View ,可通过 students/getWorstStudents
url 访问。
关于python - 如何将 url 路由到 Django 和 DRF 类的特定方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32418600/