简体   繁体   中英

Add properties to Google Datastore entity dynamically in App Engine Python (Flexible environment)

Problem

  • I want to add properties to an existing entity like an Expando Class .

Question

  • How to add properties to Google Datastore entity dynamically in App Engine Python (Flexible environment).

Development Environment

  • App Engine Python (Flexible environment).
  • Python 3.6

Tried → Error

Best regards,

This depends a little bit on how you want your application to work, but you can do something similar by using the Python Client for Google Cloud Datastore , which does work in Python3.X.

For example, you can update an already existing entity with this library by doing the following:

from flask import Flask
from google.cloud import datastore


app = Flask(__name__)


@app.route('/')
def mainhandler():  
    client = datastore.Client()
    # Entity to update Kind and ID. Replace this values 
    # with ones that you know that exist.
    entity_kind = 'Foo-entity'
    entity_id = 123456789
    key = client.key(entity_kind, entity_id)

    entity = client.get(key)

    entity.update({
            "foo": u"bar",
            "year": 2019
        })
    client.put(entity)
    return "Entity updated"

As you can see, to update an existing entity you will need its kind and its unique ID (there is no other way around).

However, you don't need to do so when you are creating the Entity, and can just update it on the run once it has been created:

from flask import Flask
from google.cloud import datastore


app = Flask(__name__)


@app.route('/')
def mainhandler():  
    client = datastore.Client()
    entity_kind = 'Ticket-sale'
    key = client.key(entity_kind)

    ''' It is better to let Datastore create the Key 
    (unless you have some method to crate unique ID's), 
    so we call the allocate_ids method, and only keep the Key object'''
    key = client.allocate_ids(key, 1)[0]
    entity = datastore.Entity(key=key)
    entity.update({
            "foo": u"bar",
            "year": 20192
    })
    client.put(entity) # This creates the entity

    # update the entity once more with another property       
    entity.update({
            "month": u"January",
    })
    client.put(entity)
    return "Entity created"

Note that you will have to use the u"string" literal, in order to alert datastore that the string you are passing is encoded in unicode, otherwise it will show up as a string made up of random characters when accessing the property value.

As well, don't forget to update your requirements.txt file by adding the line google-cloud-datastore in order to import this library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM