#Writing code in the `asgi.py` file

8 messages · Page 1 of 1 (latest)

static crane
#

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 !!!

ebon gazelle
#

It's possible, it's illegal/trash.

Putting aside the "threading" issue, you have to consider that deploying the application via an application server like uvicorn/daphne etc, will spawn multiple workers. Each one of these workers will be loading this module.

static crane
#

What do you mean by saying will spawn multiple workers ? If I deploy the site, the code in asgi.py only launches once. I think I don't get it when you say will spawn multiple workers ahah 😅.
Thank you for your answer !!!!!

ebon gazelle
#

What are you using to run your asgi application right now ?

static crane
#

I'm using daphne to run my application.

ebon gazelle
#

well, i'm not familiar with daphne, I presume there is a worker aspect to it, from a cursory reading it seems that daphne doesn't support workers by default, it runs one instance of the application. [the docs mention that you could use other tools to spawn multiple instances]

If you end up needing to run multiple instances, that will make the above added block of code run more than once.

#

I'd suggest running such a thing as a separate service outside the scope of application.asgi

static crane
#

Mhmhmhmhm 🤔 Okay I see I see.
So I think I'll look a little more into the daphne documentation. I'll do that.