Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load static data on django startup using AppConfig ready method in Django 1.7

I have some static location data to load so that it is available throughout the application like an in-memory cache.

I tried to override ready() on AppConfig but data isn't loaded from the database, also ready() is getting called twice.

from django.apps import AppConfig


class WebConfig(AppConfig):
    name = 'useraccount'
    verbose_name = 'User Accounts'
    locations = []

   def ready(self):
        print("Initialising...")
        location = self.get_model('Location')
        all_locations = location.objects.all()
        print(all_locations.count())
        self.locations = list(all_locations)

any hints?

like image 830
Chirdeep Tomar Avatar asked Oct 31 '22 13:10

Chirdeep Tomar


1 Answers

Well, the docs ( https://docs.djangoproject.com/en/1.7/ref/applications/#django.apps.AppConfig.ready ) tell you to avoid using database calls in the ready() function, and also that it may be called twice.

Avoiding the double-call is easy:

def ready(self):
    if self.has_attr('ready_run'): return
    self.ready_run = True
    ...

But I'm still trying to find the right way to do database-based initialization, too. I'll update if I find anything.

like image 137
Andrew Hows Avatar answered Nov 15 '22 08:11

Andrew Hows