python - 如何在 Django Rest 框架中允许无需身份验证即可访问基本路由

标签 python django django-rest-framework

当我在全局设置中将默认权限类别设置为 IsAuthenticated 时,如何允许访问基本路由。

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
        # 'rest_framework.permissions.AllowAny',
        'rest_framework.permissions.IsAuthenticated',

    ],
}

我知道您可以在各个 View 中设置permission_classes = [AllowAny]。 但我希望我的基本路线具有相同的即没有权限。这是我在 urls.py 中设置路由的方法

router_public = DefaultRouter()
'''
PUBLIC ROUTES HERE
'''
router_public.register(
    r'cars', car_viewset.Car_Public_Viewset, base_name='Cars')
router_public.register(
    r'planes', plane_views.Plane_Public_ViewSet, base_name='Planes')

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/admin/', include(router_admin.urls)),
    path('api/public/', include(router_public.urls)),
]

由于我已将汽车和飞机的permission_classes 设置为AllowAny,因此我无需身份验证即可访问它们。

如何对基本路线 http://localhost:8000/api/public/ 执行相同的操作因为没有与之关联的 View 。

最佳答案

您可以使用authenticated_class为不同的 View 类提供不同的权限

from rest_framework.permissions import AllowAny

class ExampleClass(viewsets.GenericViewSet):
     permission_classes = (AllowAny,)
     [...]

在你想通过api/public/访问的 View 中使用permission_classes

关于python - 如何在 Django Rest 框架中允许无需身份验证即可访问基本路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57840156/

相关文章:

python - Pandas groupby 查找公共(public)字符串

javascript - 如何将 URL 与 JQuery .getJSON() 函数一起使用

python - Django: ValueError at/save_page/- 以 10 为底的 int() 无效文字: 'My World'

django - 将 Django-rest-framework 与 Django View 一起使用是否正确

django - Django Rest框架: serializing/deserializing a calculated field

python - 如果日期范围介于开始日期和结束日期之间,则将类别附加到列

python - 计算机视觉 : Opencv Counting small circles inside big circle

angular - 如何在 Angular 2+ 中使用带有条件的多个类

python - Pandas:从保留其顺序的 2D numpy 数组创建数据框

python - Django - 如何显示数据矩阵,在每一行和每一列的末尾都有总和