sunless
sunless

Reputation: 637

Django 2: how to run code once on app initialization?

Using Django 2.2, how can I run code once after the code has been loaded but before any request is handled? (Similar to code executed in Rails initializers).

The use case is the following:

I'd like to create a pool of connections to a database and assign it to a global variable in a module but preferably not during module import.

(Initially following: https://stackoverflow.com/a/1117692/3837660, I was doing it at module import. But this is not optimal. Partly because I am facing a double import issue which I haven't solved yet and partly because I'd like to avoid creating a pool of connections at module import time.)

It should be done exactly once (no matter if that module happens to be imported twice) but at the application start (not on the first request).

=============================

EDIT:

Apparently running

python manage.py runserver localhost:8000

will call manage.py main twice. As a consequence, everything is imported twice and the ready function is also called twice.

Upvotes: 0

Views: 1456

Answers (1)

Gabriel
Gabriel

Reputation: 1149

I think you can take advantage of the django AppConfig, docs here -> https://docs.djangoproject.com/en/2.2/ref/applications/#django.apps.AppConfig

from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _


class YOURAPPNAMEConfig(AppConfig):
    name = 'YOURAPPNAME'
    verbose_name = _('VERBOSE APP NAME')

    def ready(self):
        CODE YOU WANT TO RUN ON APP READY

Let us know if this helps you.

Upvotes: 3

Related Questions