0

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.

sunless
  • 597
  • 5
  • 19

1 Answers1

2

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.

Gabriel
  • 1,014
  • 9
  • 14
  • Thanks. I guess this is indeed the right way to do it. After some debugging in turns out that when I start the server with: python manage.py runserver localhost:8000, manage.py main is called twice in a row. I don't know what to make of that. – sunless Nov 07 '19 at 13:00
  • It seems that is a behavior related to the autoreloader when a code change is detected, some more info in the reply in this thread https://stackoverflow.com/questions/28489863/why-is-run-called-twice-in-the-django-dev-server – Gabriel Nov 07 '19 at 15:47