django-rest-frameworkwebsocketdjango-channels

wAssertionError: Expected a `Response`, `HttpResponse` or `StreamingHttpResponse` to be returned from the view, but received a `<class 'coroutine'>`


Source:

async def send_stock_updates(symbol):
    while True:
        stock_info = get_one_stock_info(symbol)

        # Send stock info over WebSocket
        channel_layer = get_channel_layer()
        await async_to_sync(channel_layer.group_send)(
            'stock_updates',  # Group name
            {
                'type': 'send_stock_info',
                'stock_info': json.dumps(stock_info),
            }
        )
        await asyncio.sleep(1)

class OneStockInfoAPIView(APIView):
    async def get(self, request):
        symbol = request.query_params.get('symbol')
        if not symbol:
            return Response({'error': 'symbol parameter is required'}, status=status.HTTP_400_BAD_REQUEST)

        asyncio.create_task(send_stock_updates(symbol))

        return JsonResponse({'message': 'WebSocket updates initiated'}, status=200)

Error:

WebSocket CONNECT /ws/stock-info/ [127.0.0.1:35028]
Internal Server Error: /stock-info/
Traceback (most recent call last):
  File "/home/planet/Dhruvil/DRF/websoket/venv/lib/python3.10/site-packages/asgiref/sync.py", line 518, in thread_handler
    raise exc_info[1]
  File "/home/planet/Dhruvil/DRF/websoket/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 42, in inner
    response = await get_response(request)
  File "/home/planet/Dhruvil/DRF/websoket/venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 253, in _get_response_async
    response = await wrapped_callback(
  File "/home/planet/Dhruvil/DRF/websoket/venv/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 60, in _view_wrapper
    return await view_func(request, *args, **kwargs)
  File "/home/planet/Dhruvil/DRF/websoket/venv/lib/python3.10/site-packages/django/views/generic/base.py", line 104, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/planet/Dhruvil/DRF/websoket/venv/lib/python3.10/site-packages/rest_framework/views.py", line 511, in dispatch
    self.response = self.finalize_response(request, response, *args, **kwargs)
  File "/home/planet/Dhruvil/DRF/websoket/venv/lib/python3.10/site-packages/rest_framework/views.py", line 423, in finalize_response
    assert isinstance(response, HttpResponseBase), (
AssertionError: Expected a `Response`, `HttpResponse` or `StreamingHttpResponse` to be returned from the view, but received a `<class 'coroutine'>`

Solution

  • I met the same problem. I solved this problem by installing adrf.

    pip3 install adrf
    

    Then import APIView from adrf like this:

    from adrf.views import APIView
    
    class OneStockInfoAPIView(APIView):
        async def get(self, request):
            ...