Search code examples
python-3.xgoogle-cloud-platformgoogle-cloud-datastoredatastore

How to get entity keys(parent and custom name) in datastore using python3


I have an entity like this below..

 Name/ID                   Parent                    Rollen               email          first_name      last_name
name=CidassUID  Key(Tenant, 'CidassGroupID')    ["user","admin"]    user@email.com  user first name user last name  

Now for example i would like to query data whose email = user@email.com and get the Entity Key(both id and parent).. what i am doing write now in python is

from google.cloud import datastore
def create_client(project_id):
    return datastore.Client(project_id)
def list_user(client):
    query = client.query(kind='User')
    query.add_filter('email','=','user@email.com')
    l=query.fetch()
    l=list(l)
    print(l)

Now it is giving me the response back as

[<Entity('Tenant', 'CidassGroupID', 'User', 'CidassUID') {'first_name': 'user first name', 'last_name': 'user last name', 'email': 'user@email.com', 'Rollen': ['user', 'admin']}>]

and if i convert it to a dictionary

for entity in l:
    a=entity
d=dict(a)
print(d)

it shows the ouptut like this and remove the Entity..

{'first_name': 'user first name', 'last_name': 'user last name', 'email': 'user@email.com', 'Rollen': ['user', 'admin']}

How can i get the Entity keys e.g. ('Tenant', 'CidassGroupID') ('User', 'CidassUID') from this response?

thanks a lot!


Solution

  • This seems to work... I haven't tested it with the actual google api, but it should function the same...

    d = dict(l[0])
    keys = l[0].key.flat_path
    
    new = {keys[i]:keys[i+1] for i in range(0, len(keys), 2)}
    d.update(new)
    
    print(d)
    

    Output:

    {'first_name': 'user first name', 'last_name': 'user last name', 'email': 'user@email.com', 'Rollen': ['user', 'admin'], 'Tenant': 'CidassGroupID', 'User': 'CidassUID'}