23.01.04 13:27 작성
·
498
0
현재 Mac(M1)에서 실습 중인데 get_channel_layer() 시 로컬호스트를 계속 불러와 오류가 납니다.
run_test_helllo_channle.py
import asyncio
import os
import django
from channels.layers import get_channel_layer
os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings"
# os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
django.setup()
async def main():
channel_layer = get_channel_layer()
print(channel_layer)
message_dict = {'content': 'world'}
await channel_layer.send('hello', message_dict)
response_dict = await channel_layer.receive('hello')
is_equal = message_dict == response_dict
print("송신/수신 데이터가 같습니까?", is_equal)
asyncio.run(main())
결과
~/Documents/GitHub/Quickie test-chat !2 > python3 run_test_hello_channel.py py Quickie 13:13:37
RedisChannelLayer(hosts=[{‘address’: ‘redis://localhost:6379’}])
Traceback (most recent call last):
File “/Users/kang-yongmin/Documents/GitHub/Quickie/venv/lib/python3.10/site-packages/redis/asyncio/connection.py”, line 567, in connect
await self.retry.call_with_retry(
File “/Users/kang-yongmin/Documents/GitHub/Quickie/venv/lib/python3.10/site-packages/redis/asyncio/retry.py”, line 59, in call_with_retry
return await do()
File “/Users/kang-yongmin/Documents/GitHub/Quickie/venv/lib/python3.10/site-packages/redis/asyncio/connection.py”, line 604, in connect
reader, writer = await asyncio.openconnection(
File “/Users/kang-yongmin/.pyenv/versions/3.10.4/lib/python3.10/asyncio/streams.py”, line 47, in open_connection
transport, = await loop.createconnection(
File “/Users/kang-yongmin/.pyenv/versions/3.10.4/lib/python3.10/asyncio/base_events.py”, line 1072, in create_connection
raise OSError(‘Multiple exceptions: {}‘.format(
OSError: Multiple exceptions: [Errno 61] Connect call failed (‘::1’, 6379, 0, 0), [Errno 61] Connect call failed (‘127.0.0.1’, 6379)During handling of the above exception, another exception occurred:Traceback (most recent call last):
File “/Users/kang-yongmin/Documents/GitHub/Quickie/run_test_hello_channel.py”, line 23, in <module>
asyncio.run(main())
File “/Users/kang-yongmin/.pyenv/versions/3.10.4/lib/python3.10/asyncio/runners.py”, line 44, in run
return loop.run_until_complete(main)
File “/Users/kang-yongmin/.pyenv/versions/3.10.4/lib/python3.10/asyncio/base_events.py”, line 646, in run_until_complete
return future.result()
File “/Users/kang-yongmin/Documents/GitHub/Quickie/run_test_hello_channel.py”, line 17, in main
await channel_layer.send(‘hello’, message_dict)
File “/Users/kang-yongmin/Documents/GitHub/Quickie/venv/lib/python3.10/site-packages/channels_redis/core.py”, line 218, in send
await connection.zremrangebyscore(
File “/Users/kang-yongmin/Documents/GitHub/Quickie/venv/lib/python3.10/site-packages/redis/asyncio/client.py”, line 502, in execute_command
conn = self.connection or await pool.get_connection(command_name, **options)
File “/Users/kang-yongmin/Documents/GitHub/Quickie/venv/lib/python3.10/site-packages/redis/asyncio/connection.py”, line 1363, in get_connection
await connection.connect()
File “/Users/kang-yongmin/Documents/GitHub/Quickie/venv/lib/python3.10/site-packages/redis/asyncio/connection.py”, line 575, in connect
raise ConnectionError(self._error_message(e))
redis.exceptions.ConnectionError: Error connecting to localhost:6379. Multiple exceptions: [Errno 61] Connect call failed (‘::1’, 6379, 0, 0), [Errno 61] Connect call failed (‘127.0.0.1’, 6379).
답변 4
0
0
2023. 01. 04. 14:00
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
manage.py에 경로설정돼있습니다.
layers값은 정상적으로 출력됩니다.
~/Documents/GitHub/Quickie test-chat !3 > python3 run_test_hello_channel.py 4s py Quickie 13:59:04
{‘default’: {‘BACKEND’: ‘channels_redis.core.RedisChannelLayer’, ‘CONfIG’: {‘hosts’: [{‘host’: ‘redis-11279.c54.ap-northeast-1-2.ec2.cloud.redislabs.com’, ‘port’: 11279, ‘password’: ‘lRiJKj6xSMpubVvQ2QLNeft05INxmItmv’}]}}}
RedisChannelLayer(hosts=[{‘address’: ‘redis://localhost:6379’}])
Traceback (most recent call last):
File “/Users/kang-yongmin/Documents/GitHub/Quickie/venv/lib/python3.10/site-packages/redis/asyncio/connection.py”, line 567, in connect
await self.retry.call_with_retry(
File “/Users/kang-yongmin/Documents/GitHub/Quickie/venv/lib/python3.10/site-packages/redis/asyncio/retry.py”, line 59, in call_with_retry
return await do()
File “/Users/kang-yongmin/Documents/GitHub/Quickie/venv/lib/python3.10/site-packages/redis/asyncio/connection.py”, line 604, in _connect
reader, writer = await asyncio.open_connection(
File “/Users/kang-yongmin/.pyenv/versions/3.10.4/lib/python3.10/asyncio/streams.py”, line 47, in open_connection
transport, _ = await loop.create_connection(
File “/Users/kang-yongmin/.pyenv/versions/3.10.4/lib/python3.10/asyncio/base_events.py”, line 1072, in create_connection
raise OSError(‘Multiple exceptions: {}‘.format(
OSError: Multiple exceptions: [Errno 61] Connect call failed (‘::1’, 6379, 0, 0), [Errno 61] Connect call failed (‘127.0.0.1’, 6379)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File “/Users/kang-yongmin/Documents/GitHub/Quickie/run_test_hello_channel.py”, line 25, in <module>
asyncio.run(main())
File “/Users/kang-yongmin/.pyenv/versions/3.10.4/lib/python3.10/asyncio/runners.py”, line 44, in run
return loop.run_until_complete(main)
File “/Users/kang-yongmin/.pyenv/versions/3.10.4/lib/python3.10/asyncio/base_events.py”, line 646, in run_until_complete
return future.result()
File “/Users/kang-yongmin/Documents/GitHub/Quickie/run_test_hello_channel.py”, line 19, in main
await channel_layer.send(‘hello’, message_dict)
File “/Users/kang-yongmin/Documents/GitHub/Quickie/venv/lib/python3.10/site-packages/channels_redis/core.py”, line 218, in send
await connection.zremrangebyscore(
File “/Users/kang-yongmin/Documents/GitHub/Quickie/venv/lib/python3.10/site-packages/redis/asyncio/client.py”, line 502, in execute_command
conn = self.connection or await pool.get_connection(command_name, **options)
File “/Users/kang-yongmin/Documents/GitHub/Quickie/venv/lib/python3.10/site-packages/redis/asyncio/connection.py”, line 1363, in get_connection
await connection.connect()
File “/Users/kang-yongmin/Documents/GitHub/Quickie/venv/lib/python3.10/site-packages/redis/asyncio/connection.py”, line 575, in connect
raise ConnectionError(self._error_message(e))
redis.exceptions.ConnectionError: Error connecting to localhost:6379. Multiple exceptions: [Errno 61] Connect call failed (‘::1’, 6379, 0, 0), [Errno 61] Connect call failed (‘127.0.0.1’, 6379).
2023. 01. 04. 14:15
.env 파일에 환경변수라 기입되어있고, settings에서 이를 읽어들여 CHANNEL_LAYERS 환경변수가 정확히 세팅이 되면, run_ 파일의 실행은 반드시 잘 수행되어야 합니다.
settings.CHANNEL_LAYERS 값이 redislabs를 가리키는 데, 채널레이어 통신에서 localhost를 가리킬 리가 없습니다.
제 코드 저장소의 코드를 받아서, .env 파일을 복사해서 적용하시고, python run_test_helllo_channle.py 해보시겠어요?
https://github.com/pyhub-kr/course-django-channels-basic
해보시고 동일한 오류가 발생하신다면, 현재의 프로젝트를 압축해서 me@askcompany.kr 이메일로 보내주시겠어요?
화이팅입니다. :-)
0
2023. 01. 04. 13:44
redislabs의 서버를 사용하려하고 있습니다.
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 4.1.5.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""
from pathlib import Path
from environ import Env
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
env = Env()
env_path = BASE_DIR / ".env"
if env_path.exists():
with env_path.open(encoding="utf8") as f:
env.read_env(f, overwrite=True)
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-zlx#3$sp$wca%lnq2k4)6@lz+8aak(n!buko-%(o8=__!ht=5o'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'channels',
'daphne',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app',
]
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 = 'mysite.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 = 'mysite.wsgi.application'
ASGI_APPLICATION = 'mysite.asgi.application'
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
#django channels layer
if "CHANNEL_LAYER_REDIS_URL" in env:
channel_layer_redis = env.db_url("CHANNEL_LAYER_REDIS_URL")
CHANNEL_LAYERS = {
"default" : {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONfIG": {
"hosts": [
{
"host": channel_layer_redis["HOST"],
"port": channel_layer_redis.get("PORT") or 6379,
"password": channel_layer_redis["PASSWORD"],
}
]
}
}
}
# Password validation
# https://docs.djangoproject.com/en/4.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/4.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
.env
CHANNEL_LAYER_REDIS_URL=redis://:lRiJKj6xSMpubVvQ2QLNft05INxmItmv@redis-11279.c54.ap-northeast-1-2.ec2.cloud.redislabs.com:11279
쉘에서는 다음과 같이 잘 작동하고 있습니다.
~/Documents/GitHub/Quickie test-chat !3 > python3 manage.py shell 37s py Quickie 13:41:59
Python 3.10.4 (main, Jan 3 2023, 21:09:20) [Clang 14.0.0 (clang-1400.0.29.202)] on darwin
Type “help”, “copyright”, “credits” or “license” for more information.
(InteractiveConsole)
>>> from django.conf import settings
>>> print(settings.CHANNEL_LAYERS)
{‘default’: {‘BACKEND’: ‘channels_redis.core.RedisChannelLayer’, ‘CONfIG’: {‘hosts’: [{‘host’: ‘redis-11279.c54.ap-northeast-1-2.ec2.cloud.redislabs.com’, ‘port’: 11279, ‘password’: ‘lRiJKj6xSMpubVvQ2QLNft05INxmItmv’}]}}}
>>> exit()
2023. 01. 04. 13:50
run_test_helllo_channle.py 수행 시에는 .env 내역이 로딩이 안 된 듯 한데요. 이상하네요. .env 파일의 경로가 manage.py 파일이 있는 경로에 있나요?
run_test_helllo_channle.py 파일에서 django.setup() 이후에 settings.CHANNEL_LAYERS 값을 출력해보시겠어요?
--
그리고, 질답이 해결된 후에 redislabs.com 에서 레디스 서버의 비밀번호를 바꾸실 수 있거든요. 위에서 비밀번호가 노출되었으니, 꼭 변경해주세요. :-)
0
2023. 01. 04. 13:34
안녕하세요.
run_test_helllo_channle.py 실습은 레디스가 구동 중 인지, settings.py의 레디스 설정이 현 장고 프로젝트에 제대로 적용되어있는 지 확인하는 과정입니다.
레디스 서버는 redislabs 의 서버를 쓸려고 하시는 것인가요? 아니면 로컬에 레디스 서버를 설치하셨나요?
보여주신 오류 마지막에 아래의 메세지가 있습니다. localhost:6379 로 접속을 시도했는 데 접속에 실패했다고 합니다. 장고 프로젝트에서는 로컬의 레디스 서버에 접속 시도를 했네요. 만약 redislabs를 쓸려고 하셨다면 환경변수 적용이 안 되었거나, settings.py 에서 수정된 코드파일이 저장이 안 되었을 수도 있습니다.
redis.exceptions.ConnectionError: Error connecting to localhost:6379. Multiple exceptions: [Errno 61] Connect call failed (‘::1’, 6379, 0, 0), [Errno 61] Connect call failed (‘127.0.0.1’, 6379).
차근 차근 확인해보시구요.
settings.py 에 적용하신 내역과 .env 내역, 그리고 어떤 레디스 서버를 사용하시는 지 알려주시겠어요?
그리고 python manage.py shell 명령으로 장고 쉘을 구동하신 후에, 아래 코드 수행 결과도 알려주시겠어요?
from django.conf import settings
print(settings.CHANNEL_LAYERS)
해결방법은 멀리 있지 않습니다.
차근차근 화이팅입니다. :-)
2023. 01. 04. 15:12
옙. 차근차근 확인해보세요.
감사드리고, 화이팅입니다. :-)