I am wanting to use Redis queues to store updates that are sent to the Websocket, so that disconnected players (offline) who become reconnected can then be sent the queued messages. I am using the free Upstash redis db, doing a test run in a view shows that the connection and commands work. However inside my consumer 'def connect(self):', I am able to connect but then the redis server immediately closes the connection. Why is it working inside my view but not inside the AsyncWebsocketConsumer?
Some variations I have tried:
1. Creating redis instance globally at top of file rather than in the connect method
2. from upstash_redis import Redis
3. Synchronous redis call instead of redis.asyncio
poetry run daphne -b 0.0.0.0 -p 8000 app.asgi:application
# /consumers.py
import redis.asyncio as redis
class TaskUpdatesConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.r = redis.StrictRedis(
host=os.getenv("REDIS_HOST"),
port=os.getenv("REDIS_PORT"),
password=os.getenv("REDIS_PASSWORD"),
ssl=True,
decode_responses=True,
)
print("UPSTASH REDIS = ", await self.r.ping())
These are the logs from Upstash
14:19:33.183 [0 89.205.129.243:4884] AUTH "(redacted)"
14:19:33.268 [0 89.205.129.243:4884] PING
And these are the logs from Daphne server
127.0.0.1:56715 - - [17/Mar/2025:13:19:32] "WSCONNECTING /game_updates/53/19/" - -
UPSTASH REDIS = True
2025-03-17 13:19:32,833 ERROR Exception inside application: Connection closed by server.
Traceback (most recent call last):
File "/home/keisler/.cache/pypoetry/virtualenvs/backend-0Uga-fli-py3.11/lib/python3.11/site-packages/channels/routing.py", line 48, in __call__
return await application(scope, receive, send)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/keisler/.cache/pypoetry/virtualenvs/backend-0Uga-fli-py3.11/lib/python3.11/site-packages/channels/routing.py", line 118, in __call__
return await application(
^^^^^^^^^^^^^^^^^^
File "/home/keisler/.cache/pypoetry/virtualenvs/backend-0Uga-fli-py3.11/lib/python3.11/site-packages/channels/consumer.py", line 95, in app
return await consumer(scope, receive, send)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/keisler/.cache/pypoetry/virtualenvs/backend-0Uga-fli-py3.11/lib/python3.11/site-packages/channels/consumer.py", line 58, in __call__
await await_many_dispatch(
File "/home/keisler/.cache/pypoetry/virtualenvs/backend-0Uga-fli-py3.11/lib/python3.11/site-packages/channels/utils.py", line 57, in await_many_dispatch
await task
redis.exceptions.ConnectionError: Connection closed by server.