gpt4 book ai didi

python-3.x - 值错误 : Unknown protobuf attr type when tried to put a nested dict/entity

转载 作者:太空宇宙 更新时间:2023-11-03 15:37:45 24 4
gpt4 key购买 nike

我尝试使用 Python 将嵌套的 entity/dict放入 到数据存储中,

metadata_row = dict()
metadata_row['batch_id'] = str(uuid1())
metadata_row['table_ok'] = True
metadata_row['table_name'] = 'metadata'
metadata_row['num_rows'] = 1
metadata_row['violations'] = []
metadata_row['errors'] = []

metadata_row['time'] = {}
metadata_row['time']['total_time'] = 82.42656564712524
metadata_row['time']['mod1'] = 5.940682411193848
metadata_row['time']['mod2'] = 19.16786551475525
metadata_row['time']['mod3'] = 31.617812633514404
metadata_row['time']['mod4'] = 0.00038933753967285156
metadata_row['time']['mod5'] = 53.35780310630798

with self.client.transaction():

entities = [Entity(self.client.key('metadata')) for i in range(len([metadata_row]))]

for entity, update_dict in zip(entities, [metadata_row]):
entity.update(update_dict)

self.client.put_multi(entities)

我使用datastore emulator测试了它,但是我得到了以下错误,

ValueError: Unknown protobuf attr type <class 'dict'>

我想知道如何解决这个问题。我还想知道 datastore 本身是否支持嵌套字典,因为它不必为内部字典创建 entity,即 time这种情况。

更新。我在 metadata_row 中为关键 time 添加了一个内部实体来解决问题。

client = datastore.Client()
metadata_row['time'] = datastore.Entity(key=client.key('time'))

metadata_row['time']['total_time'] = 82.42656564712524
metadata_row['time']['mod1'] = 5.940682411193848
metadata_row['time']['mod2'] = 19.16786551475525
metadata_row['time']['mod3'] = 31.617812633514404
metadata_row['time']['mod4'] = 0.00038933753967285156
metadata_row['time']['mod5'] = 53.35780310630798

# code for put_multi()

最佳答案

def convert(obj, client, key):
"""
:param obj: dict
:param client: datastore client
:param key: Generated as client.key("your_table", "your_key")
:return: datastore.Entity
"""
if isinstance(obj, list):
return [convert(item, client, None) for item in obj]
elif isinstance(obj, dict):
entity = datastore.Entity(key)
for key in obj:
entity[key] = convert(obj[key], client, None)
return entity
else:
return obj

请提出任何改进或替代建议,因为 Google Cloud Datastore 目前没有建议将 JSON 转换为实体的方法。

关于python-3.x - 值错误 : Unknown protobuf attr type <class 'dict' > when tried to put a nested dict/entity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42511506/

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