How to Restart a Django App via API After Modifying settings.py?
I am working on a Django project where I dynamically add new languages via an API. The workflow is as follows:
- Add a new language via the API (http://localhost:8000/core/swagger/).
- Via API /generate/ Generate the .mo and .po files after adding the language.
- The new language is added to languages.json, which is loaded into settings.py at startup.
- To apply the new language, Django needs to be restarted.
I have tried several approaches to restart Django automatically via an API:
- ✅ Clearing Django's cache before restarting.
- ✅ Using a .sh script to kill the process and restart Django.
- ✅ Manually stopping and restarting Django (this works fine manually, but not via the script).
Issue: When calling the restart API, Django stops successfully but does not restart. The restart only works when I manually stop the server and restart it from the terminal. The script kills the PID but doesn’t properly relaunch Django. What I Need Help With: What is the best way to restart Django from within an API call? Is there a more reliable way to restart Django inside Docker as well? Why does manually stopping Django and then restarting work, but the script approach does not?
Relevant Repo with explaination on how to download the docker + other steps: https://github.com/Yemeni/ai_blog_system/
I have checked other approaches which are dynamic reload of settings.py but it's not recommended as per the django docs
What is the best way to restart Django from within an API call? Is there a more reliable way to restart Django inside Docker as well?
The best way is not to restart. If data is dynamic, it means you typically store and retrieve it from the database.
Restarting a (Django) webserver through an API does not make much sense. It is an evident exploit for a Denial of Service (DoS) attack: you just ask a restart over and over again, and the web server is only responsive for a few milliseconds in between.
It also can cause other vulnerabilities: if a person somehow manages to change a file, a reload means that person can run arbitrary code, which is a severe problem. Usually the idea is to clone the files from a repository you check and immediately run the server with these files, and thus don't reload when a file changes.
So I think you should move the problem from .po
files, which are used for static translations, to tools like django-parler
or django-translated-fields
. These move the problem to the database: for example store for a field that needs translation, it makes name
, name_en
, name_fr
, name_ar
, and so on, and select the correct field based on the language of the request.