当我在全局设置中将默认权限类别设置为 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/