简体   繁体   中英

How to set date property for Google Cloud Datastore entity when using Google Cloud Functions?

Cannot find an effective way to set 'Date time' for a property when creating an entity in Cloud Datastore using Cloud Functions

I am using a Python 3.7 Cloud Function which takes a JSON file as input. The JSON has an array of objects, which are read one by one to create a datastore entity object, which is then written to the datastore. In datastore all properties are stored as 'string'. I would like the date fields to be stored as 'Date time' property of the Cloud Datastore entity.

dsclient = datastore.Client(os.environ.get('project_id')) 
client = storage.Client()
bucket = client.get_bucket(event['bucket'])
blob = bucket.blob(event['name'])
input_bytes = blob.download_as_string()
input_string = input_bytes.decode("utf-8")
obj = json.loads(input_string)
length = len(obj[kind])     

for i in range(0, length):
    key = obj[kind][i]['Key']
    score = create_score(obj[kind][i], key, ns)
    dsclient.put(score)

def create_score(score, key, ns): 
    """creates the score datastore entity"""
    pkey = dsclient.key(kind, key, namespace='test')
    score_entity = datastore.Entity(
        key=pkey,        
        exclude_from_indexes=exclude_index_list
    )
    score_entity.update(score)

    return score_entity

The statement score_entity.update(score) creates all properties as Strings. Is there a way I can specify the datatypes of each property on creation? I have seen that this is possible using the Python nbd model on App Engine. But I am not using App Engine to create the entity, it is a Cloud Function.

You need to make sure that the property is a datetime.datetime , not a datetime.date or another type of object (including strings).

You should be able do something like:

score_entity = datastore.Entity(
    key=pkey,        
    exclude_from_indexes=exclude_index_list
)
score_entity["your_datetime"] = datetime.datetime.now()

...

client.put(score_entity)

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