【问题标题】:How to route an url to an specific method of a class Django and DRF如何将 url 路由到类 Django 和 DRF 的特定方法
【发布时间】:2015-12-01 19:47:48
【问题描述】:

我是 python 世界的新手,现在我用 Django 1.8 和 Rest Framework 构建一个应用程序,我想创建一个类视图来干燥我的代码。

例如,我想为我的系统中的学生提供班级视图

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 framework JWT Auth http://getblimp.github.io/django-rest-framework-jwt/ 用于令牌认证。

如何限制访问权限,只允许经过身份验证的用户可以访问此网址?

提前谢谢你!

【问题讨论】:

    标签: python django routing django-rest-framework pycharm


    【解决方案1】:

    routersviewsets 一起使用。

    首先,从ModelViewSet 而不是APIView 子类化您的视图。其次,在 getWorstStudents 方法中使用 @list_route 装饰器。第三,用路由器将urls.py 中的所有内容绑定起来。

    它应该看起来像(我没有测试过代码):

    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 的视图,可从students/getWorstStudents url 访问。

    【讨论】:

      【解决方案2】:

      您可以像任何其他 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.

      【讨论】:

      • 嗨。感谢您的回答我有一个问题,如果我想处理多个发布路线会发生什么,例如: set_note_of_student() 和 set_email_of_student() 如何为每种方法分配特定路线?再次感谢您。
      • 您可以响应标准的 HTTP 方法:GETPOSTPUT 等。在此方法中,您可以在返回 Response 之前调用您想要的任何其他方法。我理解你的问题,你可以使用 routers 和 ViewSets。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-10
      • 1970-01-01
      • 1970-01-01
      • 2018-05-19
      • 2015-09-04
      • 2014-08-19
      • 2018-02-21
      相关资源
      最近更新 更多