ConnectionRefusedError: [Errno 10061] Connect call failed ('127.0.0.1', 6379) WebSocket DISCONNECT /ws/chat/lobby/ [127.0.0.1:56602]

Viewed 8043

Here, I need to connect another channel using web sockets in django channels. I can't connect to the another channel, it showing error like this.

consumers.py

import json
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer

class ChatConsumer(WebsocketConsumer):
    def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'chat_%s' % self.room_name

        # Join room group
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )

        self.accept()

    def disconnect(self, close_code):
        # Leave room group
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )

    # Receive message from WebSocket
    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        # Send message to room group
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': message
            }
        )

    # Receive message from room group
    def chat_message(self, event):
        message = event['message']

        # Send message to WebSocket
        self.send(text_data=json.dumps({
            'message': message
        }))

routing.py*(In django project)*

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import chat.routing

application = ProtocolTypeRouter({
    
    'websocket': AuthMiddlewareStack(
        URLRouter(
            chat.routing.websocket_urlpatterns
        )
    ),
})

routing.py*(In chat app)*

from django.urls import re_path

from .consumers import ChatConsumer

websocket_urlpatterns = [
    re_path(r'ws/chat/(?P<room_name>\w+)/$',ChatConsumer),
]

views.py

from django.shortcuts import render

def index(request):
    return render(request, 'chat/index.html')

def room(request, room_name):
    return render(request, 'chat/room.html', {
    'room_name': room_name
    })

urls.py*(In chat App)*

 
from django.contrib import admin
from django.urls import path
from  .views import index,room

app_name = 'chat'
urlpatterns = [
   
     path('', index, name='index'),
     path('<str:room_name>/', room, name='room'),
]

urls.py*(In main project folder)*

 
from django.contrib import admin
from django.urls import path,include
from chat.views import index

urlpatterns = [
    path('admin/', admin.site.urls),
     path('chat/',include('chat.urls',namespace = 'chat')),
]

settings.py

 

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '_94me+sc-lcgo-eo1zrf%!t!q8$rk2b)%e-58u^h2d#v8gzk#j'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'channels',
    'chat'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'justchat.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'justchat.wsgi.application'
ASGI_APPLICATION = 'justchat.routing.application'
CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            "hosts": [('127.0.0.1', 6379)],
        },
    },
}

# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': str(BASE_DIR / 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_URL = '/static/'

2 Answers

You forgot to run redis server.

In official tutorial it is done via docker image. At first, you need to install docker. After that run redis image at 6379 port:

docker run -p 6379:6379 -d redis:5

Update:

If you are using Windows, some troubles may arise. django-channels comes packaged with redis and in-memory channel layers. Generally, in development you don't have to use redis, just redefine channel layers backend option:

settings.py

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels.layers.InMemoryChannelLayer"
    }
}

If you are not using Docker. The Redis can be set up like this. Using Debian Linux distribution, apt package manager and systemctl.

sudo apt-get install redis

Check if it works

sudo systemctl status redis

Console output

● redis-server.service - Advanced key-value store
   Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; vendor preset: enabled)
   Active: active (running) since Wed 2021-12-29 09:59:45 EST; 6min ago
     Docs: http://redis.io/documentation,
           man:redis-server(1)
 Main PID: 10411 (redis-server)
    Tasks: 4 (limit: 4915)
   Memory: 7.1M
   CGroup: /system.slice/redis-server.service
           └─10411 /usr/bin/redis-server 127.0.0.1:6379

Dec 29 09:59:45 debian systemd[1]: Starting Advanced key-value store...
Dec 29 09:59:45 debian systemd[1]: redis-server.service: Can't open PID file /run/redis/redis-se
Dec 29 09:59:45 debian systemd[1]: Started Advanced key-value store.
Related