'cannot import name 'Channel' from 'channels'

I am using python version==3.8.10 and Django==2.2 and channels==3.0.4 . I am getting error

from channels import Channel ImportError: cannot import name 'Channel' from 'channels' (/home/kritik/py38_djanngo2.2_new/lib/python3.8/site-packages/channels/init.py)

This is how my code looks like. This is the old code when I was using channels=1.1.2 and python 2.7 and Django=1.11.13. Now when I am upgrading I am getting errors Should I need to update the code? if yes then what do I need to update?

from channels import Channel
class TestWebSocket(APIView):

    def post(self, format=None):
        try:
            REPLY_CHANNEL = self.request.data['request_channel']
            # job = Job(
            #     name= new_data[0]['change_type'],
            #     status="COS initiation has started. Please be patient.",
            # )
            # job.save()
            # Tell client task has been started

            Channel(REPLY_CHANNEL).send({
                "text": json.dumps({
                    "action": "started",
                })
            })
            return Response({"Success": "Sucess"}, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({"error": str(e)}, status=status.HTTP_400_BAD_REQUEST)

Can anyone help me on this ?



Solution 1:[1]

I'm ran into the same error with unit tests.

# Chat/tests.py

from channels import Channel
from channels.test import ChannelTestCase

class MyTests(ChannelTestCase):
    def test_a_thing(self):
        # This goes onto an in-memory channel, not the real backend.
        Channel("some-channel-name").send({"foo": "bar"})

I'm following this tutorial from the Django docs: https://channels.readthedocs.io/en/1.x/testing.html

For some reason, the channels package is not recognized. I installed channels in my virtual env with the following command:

python -m pip install -U channels

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stephan