Skip to content

Document support for http.HTTPMethod in the @action decorator added in Python 3.11. #9067

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/api-guide/viewsets.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,13 @@ The `action` decorator will route `GET` requests by default, but may also accept
def unset_password(self, request, pk=None):
...

Argument `methods` also supports HTTP methods defined as [HTTPMethod](https://docs.python.org/3/library/http.html#http.HTTPMethod). Example below is identical to the one above:

from http import HTTPMethod

@action(detail=True, methods=[HTTPMethod.POST, HTTPMethod.DELETE])
def unset_password(self, request, pk=None):
...

The decorator allows you to override any viewset-level configuration such as `permission_classes`, `serializer_class`, `filter_backends`...:

Expand Down
16 changes: 16 additions & 0 deletions tests/test_decorators.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import sys

import pytest
from django.test import TestCase

Expand Down Expand Up @@ -187,6 +189,20 @@ def test_action(request):

assert str(excinfo.value) == "@action() missing required argument: 'detail'"

@pytest.mark.skipif(sys.version_info < (3, 11), reason="HTTPMethod was added in Python 3.11")
def test_method_mapping_http_method(self):
from http import HTTPMethod

method_names = [getattr(HTTPMethod, name.upper()) for name in APIView.http_method_names]

@action(detail=False, methods=method_names)
def test_action():
raise NotImplementedError

expected_mapping = {name: test_action.__name__ for name in APIView.http_method_names}

assert test_action.mapping == expected_mapping

def test_method_mapping_http_methods(self):
# All HTTP methods should be mappable
@action(detail=False, methods=[])
Expand Down