0

I am using Django 4.0.1 with the channels extension, so I'm using the ASGI interface.

In one of my applications, I'm using it's AppConfig.ready() method to start a thread / asnyc loop - specifically the paho.mqtt package via loop_start(). If a message arrives on a subscribed topic, this application handles some business logic.

This works fine for my usecase - with the exception of two problems:

  1. It's also started when I use any manage.py command.
  2. ./manage.py runserver (with reload enabled) will spawn a second process, which results in two connections being made - and I only need one.

While I could use a filesystem-mutex to block the execution of a second application, I'd like to know, if there's a more "Django way" of solving this?

Lars
  • 5,757
  • 4
  • 25
  • 55
  • Start the loop in a separate process/script, it's a bad idea to do it on app ready since your setup could expand to include several processes. Create a management command that starts your process and call this separately – Iain Shelvington Jan 07 '22 at 22:36
  • @IainShelvington this makes a docker setup a lot harder due to a multi-process setup... isn't there any way to differentiate between a manage.py-command and an asgi process from inside django? – Lars Jan 07 '22 at 22:38
  • Run a separate container, if you are using compose create a duplicate service with a different command – Iain Shelvington Jan 07 '22 at 23:35
  • while this does solve problem 1, it does not solve problem 2. I could wrap the runserver in my own file watcher for development, but I still can't believe, that there is no way of solving this in Django itself. – Lars Jan 08 '22 at 20:19

0 Answers0