Django check at runtime if code is executed under "runserver command" or not
I've a project based on django that wrap some custom code, this code during import load some heavy file before to be executed. I need to check if imports are executed under "runserver command" or not, in this way I can prevent loading heavy files during django installation.
How can i check if code is executed under runserver command
You can probably hack this into the handle of the runserver command, through monkey patching, i.e.:
# bad idea!!
GLOBAL_VAR = {
'AS_RUNSERVER': False,
}
from django.core.management.commands.runserver import Command
old_handle = Command.handle
def new_handle(self, *args, **kwargs):
GLOBAL_VAR['AS_RUNSERVER'] = True
old_hande(self, *args, **kwargs)
Command.handle = new_handle
but I would advise to make this more clean, and work with an environment variable, like:
import sys
if os.environ('ENV_AS_RUN_SERVER') == '1':
# ...
and then run this with:
ENV_AS_RUN_SERVER=1 python manage.py runserver