首页 > 解决方案 > Django - Signal.disconnect 不断开信号

问题描述

我无法弄清楚为什么信号在我的项目disconnectpost_save不起作用。

当我打电话时PipedriveSync.objects.first().sync_with_pipedrive(),它会做一些事情,然后尝试将一些信息保存到对象中。然后,sync_pipedrivesync接收者被调用,sync_with_pipedrive()再次调用,调用sync_pipedrivesync等等。

为了避免这种循环,我创建了两种方法 -在保存实例时应该断开信号disconnect_sync然后connect_sync撤销它。但它不起作用。

我可以在调试器中看到最后一行sync_with_pipedrive-self.save(disconnect=True)调用信号。

你知道出了什么问题吗?

模型.py

class PipedriveSync(TimeStampedModel):
    pipedrive_id = models.IntegerField(null=True, blank=True)
    last_sync = models.DateTimeField(null=True, blank=True)
    last_sync_response = JSONField(null=True, blank=True)
    last_sync_success = models.NullBooleanField()
    last_backsync = models.DateTimeField(null=True, blank=True)
    last_backsync_response = JSONField(null=True, blank=True)
    last_backsync_success = models.NullBooleanField()

    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')


    def save(self,disconnect=True,**kwargs):
        if disconnect:
            PipedriveSync.disconnect_sync()
        super().save(**kwargs)
        PipedriveSync.connect_sync()

    @classmethod
    def disconnect_sync(cls):
        post_save.disconnect(sync_pipedrivesync)

    @classmethod
    def connect_sync(cls):
        post_save.connect(sync_pipedrivesync,sender=PipedriveSync)

    def sync_with_pipedrive(self):
        if self.pipedrive_id:
            action = 'update'
        else:
            action = 'create'
        relative_url = self.build_endpoint_relative_url(action)
        payload = self.get_serializer_class()(self.content_object).data
        response = None
        if action == 'create':
            response = PipeDriveWrapper.post(relative_url, payload=payload)
            if response['success']:
                self.pipedrive_id = response['data']['id']
        if action == 'update':
            response = PipeDriveWrapper.put(relative_url, payload=payload)
        try:
            success = response['success']
        except KeyError:
            success = False
        self.last_sync_success = success
        self.last_sync_response = response
        self.last_sync = now()
        self.save(disconnect=True)


@receiver(post_save, sender=PipedriveSync)
def sync_pipedrivesync(instance, sender, created, **kwargs):
    instance.sync_with_pipedrive()

标签: pythondjangodjango-signalsdjango-2.1

解决方案


推荐阅读