NDB Library for Google Cloud Datastore

2.4.2 · active · verified Sun Apr 12

google-cloud-ndb is a Python client library for Google Cloud Datastore, providing an ORM-like interface for interacting with the service. It is a modern, standalone re-implementation of the original App Engine NDB. The current version is 2.4.2, and it is part of the larger `google-cloud-python` monorepo, which has frequent releases, though individual library updates may be less frequent.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define an NDB Model, create a client, establish a context, and perform basic CRUD operations (create, read, update, delete) using `async/await`. Remember to replace 'your-gcp-project-id' with your actual Google Cloud Project ID or set the `GOOGLE_CLOUD_PROJECT` environment variable. For local development, configure `DATASTORE_EMULATOR_HOST` and ensure the Datastore emulator is running.

import os
from google.cloud import ndb
import asyncio

# For local development, point to the Datastore emulator
# Ensure you've started the emulator: `gcloud emulators datastore start`
# os.environ['DATASTORE_EMULATOR_HOST'] = 'localhost:8081'

# Replace with your actual project ID or ensure GOOGLE_CLOUD_PROJECT env var is set
project_id = os.environ.get('GOOGLE_CLOUD_PROJECT', 'your-gcp-project-id') 

class User(ndb.Model):
    name = ndb.StringProperty()
    email = ndb.StringProperty()
    created = ndb.DateTimeProperty(auto_now_add=True)

async def main():
    # The NDB client is typically created once per application lifecycle
    client = ndb.Client(project=project_id)

    # All Datastore operations must happen within a context
    async with client.context():
        # Create a new user entity
        user = User(name='Alice', email='alice@example.com')
        user_key = await user.put()
        print(f'Created user with key: {user_key.id()}')

        # Fetch the user back by key
        fetched_user = await user_key.get_async()
        if fetched_user:
            print(f'Fetched user: {fetched_user.name} ({fetched_user.email})')
        
        # Query for users
        query = User.query(User.name == 'Alice')
        users_with_name = await query.fetch_async(limit=1)
        if users_with_name:
            print(f'Query result: {users_with_name[0].name}')

        # Update a user
        fetched_user.email = 'alice.new@example.com'
        await fetched_user.put()
        print(f'Updated user email to: {fetched_user.email}')

        # Delete a user
        await user_key.delete_async()
        print(f'Deleted user with key: {user_key.id()}')

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

view raw JSON →