I've got a project based on django, that wraps some custom code.
During import, this code is loading some heavy file to be executed. I need to check whether imports are executed under "runserver command" or not. This way I can prevent loading heavy files during django installation.
How can I check if code is executed under runserver command?
2 Answers 2
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.get('ENV_AS_RUN_SERVER') == '1':
# ...
and then run this with:
ENV_AS_RUN_SERVER=1 python manage.py runserver
Comments
You can override the runserver command to do whatever you want, it's a normal management command.
# your_app/management/commands/runserver.py
from django.conf import settings
from django.contrib.staticfiles.management.commands.runserver import Command as RunserverCommand
class Command(RunserverCommand):
def add_arguments(self, parser):
super().handle(self, parser)
# you can add additional arguments here, maybe to decide whether you
# should load your file or not
def handle(self, *args, **kwargs):
. . .
# do special things here
. . .
super().handle(*args, **kwargs)
But you need to make sure the app housing this management command is installed before django.contrib.staticfiles in your INSTALLED_APPS setting.
INSTALLED_APPS = [
. . .
'your_app',
. . .
# load this after your_app so custom runserver command loads first
'django.contrib.staticfiles',
]
MY_VAR=1 python manage.py runserver, then you can usesys.environ('MY_VAR) == '1'?imported, move the actual loading and computation inside some sort of function that you can call as needed. This will also be a problem for you in scenarios like unit testing, where you need the code available and may or may not want the expensive object load.