Google Cloud Datastore REST Client (Async)

9.1.0 · active · verified Thu Apr 16

gcloud-rest-datastore is an asynchronous Python client for interacting with Google Cloud Datastore via its REST API. It is part of the `gcloud-aio` monorepo, which provides async clients for various Google Cloud services. The current version is 9.1.0, and the project releases updates to individual service clients as needed, often with shared core dependencies.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `DatastoreClient`, create an entity with a key, insert it into Datastore, and then retrieve it using `lookup`. Ensure your `GOOGLE_CLOUD_PROJECT` environment variable is set or replace 'your-project-id' directly. Authentication usually works automatically via `GOOGLE_APPLICATION_CREDENTIALS` or default GCP environment settings.

import asyncio
import os
from gcloud_rest_datastore import DatastoreClient
from gcloud_rest_datastore.entities import Key, PathElement, Entity, Property

async def main():
    project_id = os.environ.get('GOOGLE_CLOUD_PROJECT', 'your-project-id')
    if project_id == 'your-project-id':
        print("Please set GOOGLE_CLOUD_PROJECT environment variable or replace 'your-project-id' with your actual project ID.")
        return

    client = DatastoreClient(project=project_id)

    # Create a key
    key = Key(project_id=project_id, path=[PathElement(kind='Task', name='sample-task')])

    # Create an entity
    entity = Entity(
        key=key,
        properties={
            'description': Property(string_value='Learn gcloud-rest-datastore'),
            'done': Property(boolean_value=False)
        }
    )

    # Insert/Update the entity
    try:
        await client.commit(mode='NON_TRANSACTIONAL', mutations=[{'insertOrUpdate': entity}])
        print(f"Entity inserted/updated: {key.path[0].name}")

        # Lookup the entity
        results = await client.lookup(keys=[key])
        if results.found: 
            retrieved_entity = results.found[0].entity
            print(f"Retrieved entity: {retrieved_entity.properties['description'].string_value}, Done: {retrieved_entity.properties['done'].boolean_value}")
        else:
            print("Entity not found.")
            
    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        await client.close()

if __name__ == '__main__':
    asyncio.run(main())

view raw JSON →