在哪里放置django信号接收码,将它们传播到多个文件? [英] where to put django signal receiver code, spread them over multiple files?

查看:135
本文介绍了在哪里放置django信号接收码,将它们传播到多个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



然而,信号接收器不断增长,我想将它们分隔成多个文件。



我没有看到关于在哪里放置信号接收器代码的讨论。



(让我怀疑我不应该使许多信号接收器可能吗?)

解决方案

查看文档:

https://docs.djangoproject.com/en/1.8/topics/signals/#connecting-receiver-功能



这是常见的将它们放在一个单独的 signals.py 文件中,也许是项目中的每个模块一个,但是您需要确保这些文件被导入,以便您的信号接收器被注册。



如上面的文档所述,Django 1.7+现在有这种情况下的 AppConfig.ready 机制



这里有一个很好的解释:

http://chriskief.com/2014/02/28/django-1-7-signals-appconfig/



(作为您可能会做的一个例子)



基本上:

 #myapp / __ init__.py 
default_app_config ='myapp.apps.MyAppConfig'

 #myapp / apps.py 
from django.apps import AppConfig

class MyAppConfig(AppConfig):

name ='myapp'
verbose_name ='我的应用'

def ready(self):

#import signal handlers
import myapp .signals.handlers


I've put my signal receiver code in the respective model file.

However, signal receivers keep growing and I'd like to separate them over multiple files.

I haven't seen discussion on where to put signal receiver codes.

(makes me suspect that I'm not supposed to make many signal receivers maybe?)

解决方案

See the docs:
https://docs.djangoproject.com/en/1.8/topics/signals/#connecting-receiver-functions

it's common to put them in a separate signals.py file, perhaps one per module in your project, but you need to ensure that these files get imported so that your signal receivers get registered.

as detailed in the docs above, Django 1.7+ now has the AppConfig.ready mechanism for this kind of case

There's a good explanation here:
http://chriskief.com/2014/02/28/django-1-7-signals-appconfig/

(as an example of what you might do)

basically:

# myapp/__init__.py
default_app_config = 'myapp.apps.MyAppConfig'

and

# myapp/apps.py
from django.apps import AppConfig

class MyAppConfig(AppConfig):

    name = 'myapp'
    verbose_name = 'My App'

    def ready(self):

        # import signal handlers
        import myapp.signals.handlers

这篇关于在哪里放置django信号接收码,将它们传播到多个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆