I've got a situation where one of my django apps needs to perform some initialisation that includes processing the models from all the installed apps -- and it needs its own models to have been initialised also. Because of this, I can't do my initialization when the app's __init__ module is loaded, because it may be too soon for other models to have been loaded, and in any case, its own models have not been loaded.
The solution I came up with was to hook the request_started signal, do the initialisation then, and unhook the signal if initialisation completed successfully. A corollary of this is that the initialisation will only happen when running a server, and not (for example) when running a shell, or tests, or otherwise using the django framework. The code I'm using for this is below; I define an initialise() function in my app's __init__ module and then call prepare_app(initialise). Is there a better way to perform application-specific initialisation, after all apps and models have been loaded, but before other processing begins? Andrew. from django.dispatch import dispatcher from django.core.signals import request_started class InitialisationHook(object): """Self-disconnecting signal hook.""" def __init__(self, init_func, dispatcher_args): self.init_func = init_func self.dispatcher_args = dispatcher_args def __call__(self): try: self.init_func() except: raise else: # Since initialisation succeeded, don't listen for more requests dispatcher.disconnect(self, **self.dispatcher_args) def prepare_app(init_func): """ Initialise the current app by calling ``init_func`` immediately before the first request. If an exception is raised by init_func, it will be propagated through to the handler (usually causing a 500 error), and initialisation will be attempted on the next request. """ # Connect the hook, ensuring that the dispatcher keeps a reference to it dispatcher_args = dict(signal=request_started, weak=False) dispatcher.connect(InitialisationHook(init_func, dispatcher_args), **dispatcher_args) --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---