Django channels Disconnects after Handshake on deployment

i'm new to using websocket and i'm trying to use channels for a simple chat. everything works perfectly on local development but in production, when i deployed the project it doesn't work and disconnects after handshaking i don't know where the problem is and what to do

consumers.py

class ChatConsumer(AsyncWebsocketConsumer):
    async def websocket_connect(self, event):
        print("connected", event)
        await self.accept()
        Type = self.get_user_type()
        if Type == "Pationt":
            id = self.scope["session"]["User_id"]
            user = UserInfo.objects.first()
            # user = await self.get_pationt_object(id)
        else:
            id = self.scope["session"]["Provider_id"]
            user = Providers.objects.first()
            # user = await self.get_doctor_object(id)
        chat_room = f"user_chatroom_{user.id}"
        self.chat_room = chat_room
        await self.channel_layer.group_add(chat_room, self.channel_name)

    async def websocket_receive(self, event):
        print("receive", event)
        received_data = json.loads(event["text"])
        msg = received_data.get("message")
        sent_by_id = received_data.get("sent_by")
        send_to_id = received_data.get("send_to")
        thread_id = received_data.get("thread_id")

        if not msg:
            print("Error:: empty message")
            return False
        Type = self.get_user_type()
        if Type == "Pationt":
            sent_by_user = await self.get_pationt_object(sent_by_id)
            send_to_user = await self.get_doctor_object(send_to_id)
        else:
            sent_by_user = await self.get_doctor_object(sent_by_id)
            send_to_user = await self.get_pationt_object(send_to_id)
        thread_obj = await self.get_thread(thread_id)
        if not sent_by_user:
            print("Error:: sent by user is incorrect")
        if not send_to_user:
            print("Error:: send to user is incorrect")
        if not thread_obj:
            print("Error:: Thread id is incorrect")

        mess = await self.create_chat_message(thread_obj, msg)
        print(mess)
        other_user_chat_room = f"user_chatroom_{send_to_id}"
        response = {"message": msg, "sent_by": sent_by_user.id, "thread_id": thread_id}

        # await self.send({"type": "websocket.send", "text": json.dumps(response)})
        await self.channel_layer.group_send(
            other_user_chat_room, {"type": "chat_message", "text": json.dumps(response)}
        )

        await self.channel_layer.group_send(
            self.chat_room, {"type": "chat_message", "text": json.dumps(response)}
        )

    # Receive message from room group

    async def websocket_disconnect(self, event):
        print("disconnect", event)

    async def chat_message(self, event):
        received_data = json.loads(event["text"])
        thread_id = received_data["thread_id"]
        await self.send(
            {
                "type": "websocket.send",
                "text": json.dumps(
                    {
                        "message": received_data["message"],
                        "sent_by": received_data["sent_by"],
                        "thread_id": thread_id,
                    }
                ),
            }
        )

    @database_sync_to_async
    def get_pationt_object(self, user_id):
        user = UserInfo.objects.get(id=user_id)
        return user

    @database_sync_to_async
    def get_doctor_object(self, user_id):
        user = Providers.objects.get(id=user_id)
        return user

    @database_sync_to_async
    def get_thread(self, thread_id):
        qs = Thread.objects.filter(id=thread_id)
        if qs.exists():
            obj = qs.first()
        else:
            obj = None

        return obj

    @database_sync_to_async
    def create_chat_message(self, thread, msg):
        Type = self.get_user_type()
        if Type == "Pationt":
            mess = ChatMessage.objects.create(
                thread=thread, Pationt=thread.Pationt, message=msg
            )
        else:
            mess = ChatMessage.objects.create(
                thread=thread, Doctor=thread.Doctor, message=msg
            )
        return mess

    def get_user_type(self):
        try:
            self.scope["session"]["Provider_id"]
            return "Doctor"
        except:
            self.scope["session"]["User_id"]
            return "Pationt"

routing.py

websocket_urlpatterns = [
    re_path(r"chat", consumers.ChatConsumer.as_asgi()),
]

asgi.py

import os

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator
from django.core.asgi import get_asgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings")
django_asgi_app = get_asgi_application()

import RealTimes.routing

application = ProtocolTypeRouter(
    {
        "http": django_asgi_app,
        "websocket": AllowedHostsOriginValidator(
            AuthMiddlewareStack(URLRouter(RealTimes.routing.websocket_urlpatterns))
        ),
    }
)

settings.py


CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("zanjebilredis-wfn-service", 6379)],
            # 'hosts':[os.environ.get('REDIS_URL','redis://localhost:6379')] #for Production use
        },
        "ROUTING": "RealTimes.routing.websocket_urlpatterns",
    },
}

Back to Top