em1208 / adrf

Async support for Django REST framework
Other
449 stars 25 forks source link

Error with decorators in method #20

Closed OmarSRolo closed 7 months ago

OmarSRolo commented 1 year ago

I am using this ViewSet:

from adrf.viewsets import ViewSet
from drf_yasg.utils import swagger_auto_schema
from rest_framework.response import Response
def user_permission(permission: str, status: int = 403):
    def int_permission(func):
        def function(self, request, **kwargs):
            if permission == "superuser" and not request.user.is_superuser:
                return Response([_("You don't have access to the resource")], status=status)
            if not request.user.has_perm(permission):
                return Response([_("You don't have access to the resource")], status=status)
            return func(self, request, **kwargs)

        return function

    return int_permission
class Testing(ViewSet):
    @swagger_auto_schema(request_body=AcceptRequestDTO, responses={"200": ResponseShortDTO()})
    @user_permission("orders.change_requests")
    async def accept(self, request):
        return Response({"complete": , "message": "", "data": ""}, status=200)

And the error is:

assert isinstance(response, HttpResponseBase), (
AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'coroutine'>`
em1208 commented 1 year ago

Hi @OmarSRolo, async def accept(self, request) is an async function so your decorator should be implemented as follows:

def user_permission(permission: str, status: int = 403):
    def int_permission(func):
        async def function(self, request, **kwargs):
            if permission == "superuser" and not request.user.is_superuser:
                return Response([_("You don't have access to the resource")], status=status)
            if not request.user.has_perm(permission):
                return Response([_("You don't have access to the resource")], status=status)
            return await func(self, request, **kwargs)

        return function

    return int_permission

Let me know if it solves your problem!