Django Signals:如何初始化绑定?

时间:2015-08-12 19:21:59

标签: python django

我在应用的__init__.py文件中导入信号文件。当我运行manage.py runserver时发生问题我发现__init__.py导入了两次,而我的回调运行了两次。

但是,当我运行manage.py shell时,它__init__.py按预期工作(一次)

(Django 1.8.3)

app/__init__.py

print 'Hello!'
import signals

应用程序/ models.py:

from django.db import models

class RemoteTask(models.Model):
    title = models.CharField(max_length=50)

class RemoteTaskStatus(models.Model):
    remote_task = models.IntegerField()
    status = models.IntegerField()

应用程序/ signals.py:

print '------> app/signals.py'

from django.db.models.signals import post_save
from django.dispatch import receiver
from app.models import RemoteTask, RemoteTaskStatus

@receiver(post_save, sender=RemoteTask)
def status_new(sender, **kwargs):
    print '---------> Running callback'
    if kwargs.get('created', 'False') is True:
        instance = kwargs['instance']
        RemoteTaskStatus.objects.create(
            remote_task=instance,
            status=0
        )

示例输出:

$ ./manage.py runserver
Hello!
------> app/signals.py
Hello!
------> app/signals.py
Performing system checks...

System check identified no issues (0 silenced).
August 12, 2015 - 19:50:38
Django version 1.8.3, using settings 'signal_loca.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Angel Velasquez的解决方案: app/__init__.py

print 'Hello!'
import app.signals

2 个答案:

答案 0 :(得分:5)

signals.py方法中导入AppConfig.ready以防止回调被注册两次。以下是推荐的方法:

my_awesome_project/
|-- app/
|   |-- __init__.py   <-- set default_app_config here
|   |-- apps.py       <-- define your AppConfig subclass here
|   |-- models.py
|   |-- signals.py    <-- define your signal handling functions here
|-- other_app/
|-- my_awesome_project/
    |-- __init__.py
    |-- settings.py
    |-- wsgi.py

应用/ __初始化__。PY

default_app_config = 'app.apps.MyAppConfig'

应用/ apps.py

from django.apps import AppConfig

class MyAppConfig(AppConfig):
    name="app"

    def ready(self):
        from . import signals

应用/ models.py

from django.db import models

class RemoteTask(models.Model):
    title = models.CharField(max_length=50)

class RemoteTaskStatus(models.Model):
    remote_task = models.IntegerField()
    status = models.IntegerField()

应用/ signals.py

from django.db.models.signals import post_save
from django.dispatch import receiver
from app.models import RemoteTask, RemoteTaskStatus

@receiver(post_save, sender=RemoteTask, dispatch_uid="status_new_signal_on_RemoteTask_post_save")
def status_new(sender, **kwargs):
    print '---------> Running callback'
    if kwargs.get('created', 'False') is True:
        instance = kwargs['instance']
        RemoteTaskStatus.objects.create(
            remote_task=instance,
            status=0
        )

修改

dispatch_uid添加到receiver装饰者。

答案 1 :(得分:1)

嗯,我读过你正在进行测试?任何机会都是py.test?尝试删除.pyc文件或__pycache__文件夹。