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

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',
]
Вернуться на верх