How to start a background thread when django server is up?

2024/10/4 21:26:00

TL;DR In my django project, where do I put my "start-a-thread" code to make a thread run as soon as the django server is up?

First of all, Happy New Year Everyone! This is a question from a newbie so it might seem dumb. Thank you for your patience and help in advance!

Background Information
Recently I am writing a MQTT forwarding program which receives MQTT message. I'd like user to set some rules to handle messages to be forwarded so I chose django to build a web server. User can edit the rules themselves on the web page.
For the MQTT client I need to have a thread to receive MQTT message no matter if the user opens a webpage or not, so I cannot write it in the view.py. If I write a shell to start django server and my script separately, I am not sure how to pass the users settings from django server to my mqtt client script.

Question
1. Is there a way to start a background thread as soon as I typed python manage.py runserver?
2. One of the user settings is the MQTT server host, so once the user change this entry on the webpage, the background MQTT client should restart and connect to the new host. Is there any ways to achieve that?

I did some research and some likely solutions I found were django-background-tasks or Celery but I am not sure those are the right way, and I think this problem is too small to import another heavy module to deal with. Please give me some advice! If you are unclear about anything feel free to ask me!
Thank you again!

Answer

What I think you can do is to start the thread in the ready() method your AppConfig in apps.py

Here a simple example

# apps.py
from django.apps import AppConfig
from threading import Threadclass TestThread(Thread):def run(self):print('Thread running')class StackConfig(AppConfig):name = 'stack'def ready(self):TestThread().start()

If you need code from other parts of your app be aware that you cannot import this on the module level, i.e. if you try something like this in your apps.py

#apps.py
from . models import Code

an exception will be raised:

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet

In order to avoid this you need to do the import in your ready() method:

#apps.py
class StackConfig(AppConfig):name = 'stack'def ready(self):from stack.models import CodeTestThread().start()

This is decribed in the docs.

In order for all this to work make sure you start your app in your settings.INSTALLED_APPS like so

'stack.apps.StackConfig',
https://en.xdnf.cn/q/70566.html

Related Q&A

Can I use SQLAlchemy relationships in ORM event callbacks? Always get None

I have a User model that resembles the following:class User(db.Model):id = db.Column(db.BigInteger, primary_key=True)account_id = db.Column(db.BigInteger, db.ForeignKey(account.id))account = db.relatio…

Elegant way to transform a list of dict into a dict of dicts

I have a list of dictionaries like in this example:listofdict = [{name: Foo, two: Baz, one: Bar}, {name: FooFoo, two: BazBaz, one: BarBar}]I know that name exists in each dictionary (as well as the oth…

sharpen image to detect edges/lines in a stamped X object on paper

Im using python & opencv. My goal is to detect "X" shaped pieces in an image taken with a raspberry pi camera. The project is that we have pre-printed tic-tac-toe boards, and must image t…

How to change the color of lines within a subplot?

My goal is to create a time series plot for each column in my data with their corresponding rolling mean. Id like the color of the lines across subplots to be different. For example, for gym and rollin…

Cythons calculations are incorrect

I implemented the Madhava–Leibniz series to calculate pi in Python, and then in Cython to improve the speed. The Python version:from __future__ import division pi = 0 l = 1 x = True while True:if x:pi…

Python: NLTK and TextBlob in french

Im using NLTK and TextBlob to find nouns and noun phrases in a text:from textblob import TextBlob import nltkblob = TextBlob(text) print(blob.noun_phrases) tokenized = nltk.word_tokenize(text) nouns =…

How can I run a script as part of a Travis CI build?

As part of a Python package I have a script myscript.py at the root of my project and setup(scripts=[myscript.py], ...) in my setup.py.Is there an entry I can provide to my .travis.yml that will run my…

Writing nested schema to BigQuery from Dataflow (Python)

I have a Dataflow job to write to BigQuery. It works well for non-nested schema, however fails for the nested schema.Here is my Dataflow pipeline:pipeline_options = PipelineOptions()p = beam.Pipeline(o…

Python decorators on class members fail when decorator mechanism is a class

When creating decorators for use on class methods, Im having trouble when the decorator mechanism is a class rather than a function/closure. When the class form is used, my decorator doesnt get treated…

Why does comparison of a numpy array with a list consume so much memory?

This bit stung me recently. I solved it by removing all comparisons of numpy arrays with lists from the code. But why does the garbage collector miss to collect it?Run this and watch it eat your memor…