Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run code before any django management command

Tags:

django

With middleware, I can execute code at the beginning and end of each HTTP request.

With Celery tasks I can accomplish the same by using the task_prerun and task_postrun signals.

What about django management commands? Is it possible to have code that runs at the beginning (and possibly end) of each django management command? Such code must also know which django management command is about to run (or has finished running). There is a ticket about a signal on application startup which may or may not do what I want, but it's not ready anyway.

like image 520
Antonis Christofides Avatar asked Nov 03 '22 09:11

Antonis Christofides


2 Answers

As you correctly state there's no specific place in Django where you can put code that is executed at every startup...

There are some places that you might be able to 'misuse' for this purpose, eg. code in urls.py or in the models.py should be run on startup...(eg. the admin uses this circumstances for its admin.autodiscover() in urls.py).

There are also some possibilities to find out if the code is being run due to the execution of a management command; you could plainly check the command line arguments via sys.argv if they contain any management commands. Another possibilty would be to specify different settings for running the app via server/management command....

like image 107
Bernhard Vallant Avatar answered Nov 15 '22 07:11

Bernhard Vallant


If the code you need to add before/after management command doesn't require access to django models/settings then u can simply update manage.py script.

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings")

from django.core.management import execute_from_command_line
from startup import pre_management_command, post_management_command

pre_management_command(sys.argv[1], sys.argv[2:])
execute_from_command_line(sys.argv)
post_management_command(sys.argv[1], sys.argv[2:])

I am not 100% sure but I suppose post_management_command would have access to django models.

This is just basic example, In reality u will need to ensure that sys.argv has at least two entries and that the second entry doesn't start with - to prevent false positive calls like

 ./manage.py
 ./manage.py -h
 ./manage.py --help
like image 28
Ramast Avatar answered Nov 15 '22 05:11

Ramast