如何在GAE的ndb模型中创建随机缺省值?

2024-05-23 17:06:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个ndb模型

import os
class ProblemInvite(ndb.Model):
    email = nab.StringProperty(required=True)
    token = ndb.StringProperty(required=True, default=os.urandom(16).encode('hex'))

当我创建模型列表时,标记是相同的:

import logging
for email in emails:
    problem_invite = ProblemInvite(email=email_address)
    logging.exception(problem_invite.token)

奇怪的是,每封邮件的邀请令牌都是一样的,有什么问题吗?谢谢。你知道吗


Tags: 模型importtokentruemodelosemaillogging
1条回答
网友
1楼 · 发布于 2024-05-23 17:06:33

数据存储中的属性类型一次只能有一个默认值。从Property Options表:

enter image description here

因此os.urandom(16).encode('hex')表达式只计算一次。我不是100%肯定什么时候,但我怀疑它会在应用程序部署时-当数据存储模型上传。你知道吗

要解决这个问题,只需在创建实体时删除默认值并显式指定属性值。你知道吗

旁注:在ndb模型中使用默认值时,您需要特别小心更改这些默认值,因为在应用程序部署/更新时,数据存储中已存在的实体的行为(即为受影响的属性返回的数据)可能会更改。你知道吗

相关问题 更多 >