A client for NDB which manages credentials, project, namespace, and database.

class, namespace=None, credentials=None, client_options=None, database=None)[source]


An NDB client.

The NDB client must be created in order to use NDB, and any use of NDB must be within the context of a call to context().

The Datastore Emulator is used for the client if and only if the DATASTORE_EMULATOR_HOST environment variable is set.

  • project (Optional[str]) – The project to pass to proxied API methods. If not passed, falls back to the default inferred from the environment.

  • namespace (Optional[str]) – Namespace to pass to proxied API methods.

  • credentials (Optional[Credentials]) – The OAuth2 Credentials to use for this client. If not passed, falls back to the default inferred from the environment.

  • client_options (Optional[ClientOptions or dict]) – Client options used to set user options on the client. API Endpoint should be set through client_options.

  • database (Optional[str]) – Database to access. Defaults to the (default) database.

SCOPE: Optional[Tuple[str, ...]] = ('',)

The scopes required for authenticating as a Cloud Datastore consumer.

context(namespace=<object object>, cache_policy=None, global_cache=None, global_cache_policy=None, global_cache_timeout_policy=None, legacy_data=True)[source]

Establish a context for a set of NDB calls.

This method provides a context manager which establishes the runtime state for using NDB.

For example:

from import ndb

client = ndb.Client()
with client.context():
    # Use NDB for some stuff

Use of a context is required–NDB can only be used inside a running context. The context is used to manage the connection to Google Cloud Datastore, an event loop for asynchronous API calls, runtime caching policy, and other essential runtime state.

Code within an asynchronous context should be single threaded. Internally, a threading.local instance is used to track the current event loop.

In a web application, it is recommended that a single context be used per HTTP request. This can typically be accomplished in a middleware layer.