python - 如何将 url 路由到 Django 和 DRF 类的特定方法

标签 python django routes django-rest-framework pycharm

我对 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 身份验证。

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

提前谢谢您!

最佳答案

使用routersviewsets .

首先,从 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/

相关文章:

python - 在 Django 应用程序中,每个用户只允许一个事件 session

python - django FormView 中的多个 .save()

node.js - 跨文件拆分时使用 router.use 表示路由器未定义参数

java - 防止在反向路由中转义斜线

python - 从另一个脚本启动一个 python 脚本,参数在 subprocess 参数中

python - 如何在 Plotly 中作为查看器启用和禁用对数刻度?

javascript - 在 jQuery POST 之后渲染页面

python - 无法安装 Django : Command "python setup.py egg_info" failed with error code 1 in/tmp/pip-build-rcF9a5/Django/

python - Azure 事件中心 python 库

javascript - 将 VueJS 与 Rails 现有应用程序部分集成