Set action for HEAD requests (#7223)

* Test viewset action attr

* Add 'head' to viewset actions map
This commit is contained in:
Ryan P Kilby 2020-03-09 02:43:02 -07:00 committed by GitHub
parent 4a98533746
commit 908f91d8ef
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 5 deletions

View File

@ -93,6 +93,10 @@ class ViewSetMixin:
def view(request, *args, **kwargs): def view(request, *args, **kwargs):
self = cls(**initkwargs) self = cls(**initkwargs)
if 'get' in actions and 'head' not in actions:
actions['head'] = actions['get']
# We also store the mapping of request methods to actions, # We also store the mapping of request methods to actions,
# so that we can later set the action attribute. # so that we can later set the action attribute.
# eg. `self.action = 'list'` on an incoming GET request. # eg. `self.action = 'list'` on an incoming GET request.
@ -104,9 +108,6 @@ class ViewSetMixin:
handler = getattr(self, action) handler = getattr(self, action)
setattr(self, method, handler) setattr(self, method, handler)
if hasattr(self, 'get') and not hasattr(self, 'head'):
self.head = self.get
self.request = request self.request = request
self.args = args self.args = args
self.kwargs = kwargs self.kwargs = kwargs

View File

@ -37,14 +37,18 @@ class ActionViewSet(GenericViewSet):
queryset = Action.objects.all() queryset = Action.objects.all()
def list(self, request, *args, **kwargs): def list(self, request, *args, **kwargs):
return Response() response = Response()
response.view = self
return response
def retrieve(self, request, *args, **kwargs): def retrieve(self, request, *args, **kwargs):
return Response() return Response()
@action(detail=False) @action(detail=False)
def list_action(self, request, *args, **kwargs): def list_action(self, request, *args, **kwargs):
raise NotImplementedError response = Response()
response.view = self
return response
@action(detail=False, url_name='list-custom') @action(detail=False, url_name='list-custom')
def custom_list_action(self, request, *args, **kwargs): def custom_list_action(self, request, *args, **kwargs):
@ -155,6 +159,22 @@ class InitializeViewSetsTestCase(TestCase):
self.assertNotIn(attribute, dir(bare_view)) self.assertNotIn(attribute, dir(bare_view))
self.assertIn(attribute, dir(view)) self.assertIn(attribute, dir(view))
def test_viewset_action_attr(self):
view = ActionViewSet.as_view(actions={'get': 'list'})
get = view(factory.get('/'))
head = view(factory.head('/'))
assert get.view.action == 'list'
assert head.view.action == 'list'
def test_viewset_action_attr_for_extra_action(self):
view = ActionViewSet.as_view(actions=dict(ActionViewSet.list_action.mapping))
get = view(factory.get('/'))
head = view(factory.head('/'))
assert get.view.action == 'list_action'
assert head.view.action == 'list_action'
class GetExtraActionsTests(TestCase): class GetExtraActionsTests(TestCase):