Python 2.7 has reached end of supportand will bedeprecatedon January 31, 2026. After deprecation, you won't be able to deploy Python 2.7applications, even if your organization previously used an organization policy tore-enable deployments of legacy runtimes. Your existing Python2.7 applications will continue to run and receive traffic after theirdeprecation date. We recommend thatyoumigrate to the latest supported version of Python.

NDB Functions

Functions

This page describes how to use the legacy bundled services and APIs. This API can only run in first-generation runtimes in the App Engine standard environment. If you are updating to the App Engine Python 3 runtime, refer to themigration guide to learn about your migration options for legacy bundled services.
ndb.add_flow_exception(exc)
Specify that an exception shouldnot be logged, but is just part of normal program flow. (Normally, raising an exception writes a warning message to the application's logs.)

Arguments

exc
Exception class that should not be logged.

By default, the following exceptions are not logged:

  • webob.exc.HTTPException (and its subclasses)
  • ndb.Rollback
ndb.delete_multi(keys,**ctx_options)
Deletes entities identified by the passed sequence of keys.

Arguments

keys
Sequence ofkeys
**ctx_options
Context options
ndb.delete_multi_async(keys,**ctx_options)
Asynchronously deletes entities identified by the passed sequence of keys.

Arguments

keys
Sequence ofkeys
**ctx_options
Context options

Returns a list ofFuture objects. Each future's result will beNone.

ndb.get_multi(keys,**ctx_options)
Fetches entities identified by the passed sequence of keys.

Arguments

keys
Sequence ofkeys
**ctx_options
Context options

Returns a list. Each list item is either aModel instance orNone if the key wasn't found.

ndb.get_multi_async(keys,**ctx_options)
Asynchronously fetches entities identified by the passed sequence of keys.

Arguments

keys
Sequence ofkeys
**ctx_options
Context options

Returns a list ofFuture objects. Each future's result is aModel instance orNone if the key wasn't found.

ndb.in_transaction()
Returns a Boolean indicating whether a transaction is currently active.
@ndb.non_transactional
@ndb.non_transactional(allow_existing=True)
Decorator to ensure that a function runsoutside a transaction.

Arguments:

allow_existing
IfTrue (the default) and if the decorated function is called by code in a transaction, the function runs independent of the transaction. IfFalse and if the decorated function is called by code in a transaction, it raises an exception.
ndb.put_multi(entities,**ctx_options)
Stores a sequence ofModel instances.

Arguments

entities
Sequence ofModel instances
**ctx_options
Context options

Returns a list with the storedkeys.

ndb.put_multi_async(entities,**ctx_options)
Asynchronously stores a sequence ofModel instances.

Arguments

entities
Sequence ofModel instances
**ctx_options
Context options

Returns a list ofFuture objects. Each future's result will be a storedkey.

ndb.transaction(callback,**ctx_options)
Run a callback in a transaction.

Arguments

callback
Function or tasklet to be called
**ctx_options
Transaction options

Returns whatevercallback returns. Raises whatevercallback raises or aTransactionFailedError exception if the transaction fails.

To pass arguments to a callback function, use a lambda. For example,

defmy_callback(key,inc):...transaction(lambda:my_callback(Key(...),1))
ndb.transaction_async(callback,**ctx_options)
Asynchronously run a callback in a transaction.

Arguments

callback
Function or tasklet to be called
**ctx_options
Transaction options

Returns aFuture. The future returns whatevercallback returns, or raises whatevercallback raises or aTransactionFailedError if the transaction fails.

To pass arguments to a callback function, use a lambda. For example,

defmy_callback(key,inc):...transaction(lambda:my_callback(Key(...),1))
@ndb.transactional
@ndb.transactional(**ctx_options)
Decorator to make a function automatically run in a transaction.

Arguments:

This decorator can havetransaction options.

Context Options, Transaction Options

Context options allow you to run specific datastore operations with different configurations. For example, you might want to vary the read policy or the RPC deadline for individual requests. You can do this by passingcontext options to almost any operation. Some transaction-related functions taketransaction options, which include additional options on top of a set of context options.

Here are a few examples using context options. To set the RPC deadline to 1 second when reading an entity, you can use:

key.get(deadline=1)

To set the memcache timeout to 30 seconds when writing an entity, you can use:

ent.put(ndb_memcache_timeout=30)

To delete an item that has been cached and force its reload, you can use:

key.delete(use_datastore=False)

The special keyword argumentsoptions andconfig (which have identical meanings for historical reasons) allow one to specify several options as a Configuration object. This can be anndb.ContextOptions object or (for the transactional functions and decorator) anndb.TransactionOptions object. For example,key.get(options=ndb.ContextOptions(use_cache=True)) is equivalent tokey.get(use_cache=True). The options set in such an options object can be overridden by keyword parameters.

The followingcontext options are available:

OptionTypeDescription
deadlinefloatDatastore call deadline, specified as a number of seconds. (By default, the call is only interrupted by the request handler deadline.)
read_policyndb.EVENTUAL_CONSISTENCYSet this tondb.EVENTUAL_CONSISTENCY if, instead of waiting for the Datastore to finish applying changes to all returned results, you wish to get possibly-not-current results faster.
force_writesboolSpecifies whether a write request should succeed even if the app is read-only. (This only applies to user controlled read-only periods.)
use_cacheboolSpecifies whether to store entities in in-process cache; overrides in-process cache policy for this operation.
use_memcacheboolSpecifies whether to store entities in memcache; overrides memcache policy for this operation.
use_datastoreboolSpecifies whether to store entities in Datastore; overrides Datastore policy for this operation.
memcache_timeoutintMaximum lifetime for entities in memcache; overrides memcache timeout policy for this operation.
max_memcache_itemsintMaximum batch size for the auto-batching feature of theContext memcache methods. For example, with the default size ofmax_memcache_items (100), up to 100 memcache set operations will be combined into a singleset_multi operation.

For some transaction-related functions, the followingtransaction options are available (along with the inherited context options listed above):

OptionTypeDescription
xgboolAllow cross-group (XG) transactions.False by default.
propagationint

NDB provides limited support for transactions within transactions, which are known as "nested transactions".

The propagation parameter controls what happens if your code tries to start a nested transaction.

The propagation policy for@ndb.transactional defaults toALLOWED.

The propagation policy forndb.transaction() defaults toNESTED. TheNESTED policy is not supported by NDB so your code will throw aBadRequestError exception. NDB sets an unsupported default value, in this case, so that programmers are explicitly aware of the limitations of nested transactions.

The propagation parameter can be one of the following values:

ndb.TransactionOptions.NESTED
TheNESTED propagation policy would commit all changes in the outer and inner transactions together when the outer policy commits. However, if an exception is thrown in the inner transaction all changes there would get thrown out but allow the outer transaction to optionally recover and continue. TheNESTED policy is not supported. If you use this policy, your code will throw aBadRequestError exception.
ndb.TransactionOptions.MANDATORY
Always propagate an existing transaction; throw an exception if there is no existing transaction. If a function that uses this policy throws an exception, it's probably not safe to catch the exception and commit the outer transaction; the function may have left the outer transaction in a bad state.
ndb.TransactionOptions.ALLOWED
If there is an existing transaction, propagate it. If a function that uses this policy throws an exception, it's probably not safe to catch the exception and commit the outer transaction; the function may have left the outer transaction in a bad state.
ndb.TransactionOptions.INDEPENDENT
Always use a new transaction, "pausing" any existing transactions. A function that uses this policy should not return any entities read in the new transaction, as the entities are not transactionally consistent with the caller's transaction.
retriesintHow many times to retry automatically in case of transaction failures. Zero means to try once but notre-try.

In some cases, options are ignored because of caching. For example, if you specify an RPC deadline for a read operation that is satisfied from the in-context cache, the deadline is ignored. On the other hand, unrecognized options causeTypeError to be raised.

Operations with different options are grouped together when auto-batching applies. For example, if you useput_async() to write some entities withdeadline = 5 and some without specifying a deadline, and all are eligible for auto-batching, the auto-batcher will make two separate RPC calls—one for the group of entities withdeadline = 5 and one for the other group—even though the default RPC deadline is also 5! This applies even if the option specified is irrelevant to the RPC operation (for example,ndb_should_cache).

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-15 UTC.