如何使计时器恰好30秒从创建日期Django



我需要使一个操作只在30秒内可用,然后它就会过期。我有这个型号:

(操作(

status = CharField(max_length=10, default="INI")
created_at = DateTimeField(auto_now_add=True)
account = ForeignKey(Account, null=False, on_delete=CASCADE)
metadata = models.JSONField(default=dict)
external_ref = CharField(max_length=128)
expires_at = DateTimeField(default=timezone.now()+timezone.timedelta(seconds=30))

我想能够在expires_at字段中创建一个时间戳,距离created_at日期正好30秒,这就像一个超时函数,但当我运行测试时:

def test_timeout_is_30_seconds(self):
print(self.operation.created_at)
timer = self.operation.created_at + timezone.timedelta(seconds=30)
print(timer)
self.assertEqual(self.operation.expires_at, timer)

它失败了,并显示以下消息:

AssertionError: datetime.datetime(2021, 6, 22, 19, 0, 42, 537490, tzinfo=<UTC>) != datetime.datetime(2021, 6, 22, 19, 0, 45, 844588, tzinfo=<UTC>)

我不知道我是需要在类中还是直接在View中创建一个外部函数或方法,但我更喜欢模型中的默认行为,所以我不需要担心设置到期日期

如果你能帮我解决问题,我将不胜感激!:D任何提示和信息都将受到的赞赏

这是一个常见错误。定义类时,将对表达式timezone.now()+timezone.timedelta(seconds=30)求值一次,并且该值将用作每个实例的默认值。

您实际想要的是,每次创建新实例时,都要重新计算过期时间。这意味着您希望将default设置为一个函数:

def half_minute_hence():
return timezone.now() + timezone.timedelta(seconds=30)
expires_at = DateTimeField(default=half_minute_hence)

最新更新