Hello everyone !
I work on a website project with django as a backend, and I asked myself a question : is it okay to write code in the asgi.py file for utils features ?
I need to create a thread at the launch of my server for it can constantly watch a list in my redis server.
So, is it possible or it illegal/trash to do that ?
Here's an example :
"""
ASGI config for backend project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.0/howto/deployment/asgi/
"""
import os
from channels.auth import AuthMiddlewareStack
from django.core.asgi import get_asgi_application
from channels.security.websocket import AllowedHostsOriginValidator
from channels.routing import ProtocolTypeRouter, URLRouter
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
django_asgi_app = get_asgi_application()
#######################################
import redis, threading, time
def watcher():
try:
pool = redis.Redis('localhost', port=6379, decode_responses=True)
queue = 'queue'
pool.delete(queue)
except Exception as e:
print(f'ERROR REDIS [MATCHMAKING]: {e}')
return
while True:
in_queue = pool.lrange(queue, 0, -1)
print(f'\'{queue}\': {in_queue}')
time.sleep(1)
if pool.llen(queue):
print('do something')
matchmaking = threading.Thread(target=watcher)
matchmaking.start()
####################################
import game.routing
application = ProtocolTypeRouter({
'http': get_asgi_application(),
'websocket': AllowedHostsOriginValidator(
AuthMiddlewareStack(URLRouter(game.routing.websocket_urlpatterns))
),
})
Thanks alot !!!