samu
samu

Reputation: 3120

Run command only once after Django app startup

I have a django-based function that needs to be run only once in Django, when the app boots up. The tricky part is that:

I could, theoretically, just introduce a locking mechanism and let it run somewhere in AppConfig.ready() method, but that would still run in all management commands as well.

Since the app is packaged in Docker, I've been also thinking about simply wrapping the code in a separate management command and running it in the entry point, just before the app is being started. That seems to do the trick, but it will be done automatically only in that particular container - if somebody runs a local development server to work on the app on his own, he might not be aware that an additional command should be run.

I've searched through the documentation and it doesn't look like Django has a way to do this natively on its own. Perhaps there's a better approach that I can't think of?

Upvotes: 1

Views: 1351

Answers (1)

albar
albar

Reputation: 3100

I had exactly the same need. I run the startup code in AppConfig.ready(), depending on an environment variable that you have to set when you don't want the startup code to be executed.

SKIP_STARTUP = settings.DEBUG or os.environ.get('SKIP_STARTUP')
class myapp(AppConfig):
    def ready(self):
        if not SKIP_STARTUP:
            <startup stuff>

Upvotes: 0

Related Questions