我有一个带有extra action的ModelViewSet,在身份验证和授权方面,其行为需要与视图集的其他部分不同。
E.g。
class MyModelViewSet(viewsets.ModelViewSet):
authentication_classes = [SomeClass]
permission_classes = [AnotherClass]
queryset = Model.objects.some_important_ones()
serializer_class = MyModelSerializer
@list_route(methods=['post', 'options'], authentication_classes=[])
def action(self, request, *args, **kwargs):
response_data = so_something_specific(request)
return Response(response_data, status=status.HTTP_201_CREATED)
测试设置是
@pytest.fixture
def request():
return APIRequestFactory()
def test_the_data_was_created(request):
req = request.post('/api/my-model/action/', payload={}, format='json')
view = MyModelViewSet.as_view({'post': 'action'})
res = view(req)
assert res.status_code == 201
所以问题是响应总是抱怨没有提供身份验证,但操作实际上并不需要它! repr看起来像这样:
<Response status_code=401, "text/html; charset=utf-8">
内容
'{"detail":"Authentication credentials were not provided."}'
问题是,我怎样才能让callable运行起来呢?
答案 0 :(得分:0)
这最终变得非常简单。查看路由器source,我只需要传递初始化关键字参数以匹配@list_route
装饰器正在执行的操作:
view = MyModelViewSet.as_view({'post': 'action'}, **{'authentication_classes': []})