Django信号发射一次,收到两次 - 为什么?

时间:2009-09-25 17:35:10

标签: django django-signals

我正在使用Django信号,但它们似乎被接收了两次,即使发出一次。这是我正在使用的代码(它是使用上传与Django的简单包装器)...

# Signal-emitting code... emits whenever a file upload is received
# ----------------------------------------------------------------
upload_recieved = django.dispatch.Signal(providing_args=['data'])

def upload(request, *args, **kwargs):
    if request.method == 'POST':
        if request.FILES:
            print 'sending signal'
            upload_recieved.send(sender='uploadify', data=request.FILES['Filedata'])
    return HttpResponse('True')

# Signal-receiving code...
# ----------------------------------------------------------------    
def upload_received_handler(sender, data, **kwargs):
    print 'upload received handler'

print 'connecting signal'
upload_recieved.connect(upload_received_handler)

(我刚注意到我的信号拼错了)

我确定你注意到那里的印刷文件。在控制台上,这就是它所显示的内容:

(server starts)
connecting signal

...

sending signal
upload received handler
upload received handler     # << == where is this 2nd one coming from?
127.0.0.1 - - [25/Sep/2009 07:28:22] "POST /uploadify/upload/ HTTP/1.1" 200 -

(奇怪的是,为什么Django会在信号被触发后报告页面POST?)

2 个答案:

答案 0 :(得分:21)

之前发生过这种情况,这是由于您要连接两次输入信号的模块。要确保信号未连接两次,您可以设置dispatch_uid:

upload_recieved.connect(upload_received_handler, dispatch_uid="some.unique.string.id")

<强>更新 它实际上记录在这里:http://code.djangoproject.com/wiki/Signals#Helppost_saveseemstobeemittedtwiceforeachsave

答案 1 :(得分:0)

您可以检查函数中的“ created”参数是否与分别返回True和False的信号连接。

def task_feedback_status_handler(sender, instance, created, **kwargs):
do something
post_save.connect(task_feedback_status_handler, sender=Feedback)