9

I want some code in my Django app to be executed only once when server is started, not per request.

Specifically, I want to load some database tables into memory. These tables contain some 'metadata' that doesn't change per request. Like this:

ProductTypesData = None;
def loadProductTypesData():
     productTypes = ProductType.objects.all();
     for ptype in productTypes:
         ptype_data = {
             "id":ptype.id,
             "name": ptype.name,
             "description":ptype.desc
         };
         ProductTypesData.append(ptype_data);
loadProductTypesData();

Where should I put this code? Other Q/A about django initialization suggest to put it in urls.py. But importing the models in urls.py doesn't seem logical to me.

Can I just put the code in models.py? Does it get executed only once (if it is acceptable to be executed not on django start)?

NeoWang
  • 17,361
  • 24
  • 78
  • 126
  • 7
    http://stackoverflow.com/questions/6791911/execute-code-when-django-starts-once-only http://stackoverflow.com/questions/12419403/django-startup-code-executed-only-once?lq=1 http://stackoverflow.com/questions/2781383/where-to-put-django-startup-code?lq=1 http://stackoverflow.com/questions/1797046/correct-place-to-put-extra-startup-code-in-django?lq=1 http://stackoverflow.com/questions/9259844/running-startup-code-right-after-django-settings-also-for-commands?lq=1 http://stackoverflow.com/questions/14516737/django-call-a-method-only-once-when-the-django-starts-up?lq=1 – bosnjak Apr 15 '14 at 01:54
  • When you create a new question, there is a field below the "Title" textbox, that says: *Questions that may already have your answer*. Use that field to search for questions that my already have your answer before posting the question. Thanks. – bosnjak Apr 15 '14 at 01:57

0 Answers0