Django-Signal.disconnect不会断开信号

时间:2019-03-19 11:50:54

标签: python django django-signals django-2.1

我不知道为什么disconnect中的post_save信号在我的项目中不起作用。

当我调用PipedriveSync.objects.first().sync_with_pipedrive()时,它会执行某些操作,然后尝试将一些信息保存到该对象。然后,sync_pipedrivesync接收方被调用,该接收方再次调用sync_with_pipedrive(),从而调用sync_pipedrivesync等。

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

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

你知道怎么了吗?

models.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()

0 个答案:

没有答案