gpt4 book ai didi

python - 重复 StructuredProperty 中 Expando 模型的自定义属性未正确保存

转载 作者:行者123 更新时间:2023-12-01 05:21:40 27 4
gpt4 key购买 nike

我正在尝试使用 Expando模型作为重复 StructuredProperty在另一个模型中。即,我想添加不定数量的Accounts给我的User模型。如Accounts根据其类型可以具有不同的属性( Accounts 是对社交网络帐户的引用,例如 Twitter 的 OAuth 过程需要比 Facebook 更多的信息),我设计了我的 Account模型为Expando 。我已在模型定义中添加了所有基本信息,但我计划为特定社交网络添加自定义属性(例如,Twitter 的特定 access_token_secret 属性)。

1/您能否确认以下设计( Expando 重复 StructuredProperty )应该有效?

class Account(ndb.Expando):
account_type = ndb.StringProperty(required=True, choices=['fb', 'tw', 'li'])
account_id = ndb.StringProperty()
state = ndb.StringProperty()
access_token = ndb.StringProperty()

class HUser(User):
email = ndb.StringProperty(required=True, validator=validate_email)
created = ndb.DateTimeProperty(auto_now_add=True)
accounts = ndb.StructuredProperty(Account, repeated=True)

2/现在我面临的问题是:当我将 Facebook 帐户添加到我的 HUser 时例如,一切正常;然而,当我将 Twitter 帐户附加到同一个实例,并添加一个未在模型中声明的新属性时,问题就出现了,如下所示:

for account in huser.accounts:
if account.state == "state_we_re_looking_for" and account.account_type == 'tw':
# we found the appropriate Twitter account reference
account.access_token_secret = "..." # store the access token secret fetched from Twitter API
huser.put() # save to the Datastore
break

此操作应该将访问 token secret 保存在 Twitter Account 中我的实例User ,但实际上它会将其保存在 Facebook Account 中实例(索引 0 处)!

我做错了什么?

谢谢。

最佳答案

这是 ndb 如何存储 StructuredProperty 的一个基本问题。数据存储区目前没有办法存储它,所以 ndb 基本上会爆炸你的属性。

例如,考虑实体:

HUser(email='test@example.com'.
accounts=(Account(type='fb',
account_id='1',
state='1',
access_token='1'),
Account(type='tw',
account_id='2',
state='2',
access_token='2',
access_token_secret='2')))

这实际上会存储在一个实体中,如下所示:

{
email : 'test@example.com',
accounts.type : ['fb', 'tw'],
accounts.account_id : ['1', '2'],
accounts.state : ['1', '2'],
accounts.access_token : ['1', '2'],
accounts.access_token_secret : ['2']
}

因为您使用的是 ndb.Expando,ndb 不知道它应该使用 None 填充 access_token_secret 字段 Facebook 账号。当 ndb 重新填充您的实体时,它将为其看到的第一个帐户(即 facebook 帐户)填充 access_token_secret

重组数据听起来是解决此问题的正确方法,但您可能希望使 HUser 成为该 HUserAccount 的祖先,以便查询对于使用 strong consistency 的用户帐户.

关于python - 重复 StructuredProperty 中 Expando 模型的自定义属性未正确保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22185690/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com