How To Run Arbitrary Code After Django is “Fully Loaded”

前端 未结 4 1530
失恋的感觉
失恋的感觉 2020-12-17 09:46

I need to perform some fairly simple tasks after my Django environment has been \"fully loaded\".

More specifically I need to do things like Signal.disconnect(

4条回答
  •  执笔经年
    2020-12-17 10:32

    I had to do the following monkey patching. I use django 1.5 from github branch. I don't know if that's the proper way to do it, but it works for me.

    I couldn't use middleware, because i also wanted the manage.py scripts to be affected.

    anyway, here's this rather simple patch:

    import django
    from django.db.models.loading import AppCache
    
    django_apps_loaded = django.dispatch.Signal()
    
    def populate_with_signal(cls):
        ret = cls._populate_orig()
        if cls.app_cache_ready():
            if not hasattr(cls, '__signal_sent'):
                cls.__signal_sent = True
                django_apps_loaded.send(sender=None)
        return ret
    
    if not hasattr(AppCache, '_populate_orig'):
        AppCache._populate_orig = AppCache._populate
        AppCache._populate = populate_with_signal
    

    and then you could use this signal like any other:

    def django_apps_loaded_receiver(sender, *args, **kwargs):
        # put your code here.
    django_apps_loaded.connect(django_apps_loaded_receiver)
    

提交回复
热议问题