我尝试使用putentity/dict嵌套的Python放入数据存储区,

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 - ValueError:尝试放入嵌套的dict/实体时,未知的protobuf attr类型<class'dict'>,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42511506/

10-14 20:23