python - Django - Signal.disconnect 不断开信号
问题描述
我无法弄清楚为什么信号在我的项目disconnect
中post_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()
解决方案
推荐阅读
- c# - 如何计算水平投影到斜线的点
- android - Android 纵向和横向布局
- sql - 未找到“DATE_OF_BIRTH”列;SQL 语句:
- visual-c++ - C89初始化为什么MSVC会抛出错误而Mingw没有?
- java - 静态方法,返回结果并打印结果
- python - 如何在python中为不同范围的数据点分配颜色
- angular - 在 Angular 6 中调用不同的 ng-bootstrap 模式弹出窗口
- java - JPA - 如何使用来自实体继承的 criteriaBuilder.construct 填充 DTO
- html - 如何让 div 一直出现在屏幕上,即使其中没有内容
- apache-flink - 在 Flink KeyedStream 上暂停处理