API Reference

Functions

anom.get_adapter()[source]

Get the current global Adapter instance.

Returns:The global adapter. If no global adapter was set, this instantiates a adapters.DatastoreAdapter and makes it the default.
Return type:Adapter
anom.set_adapter(adapter)[source]

Set the global Adapter instance.

Parameters:adapter (Adapter) – The instance to set as the global adapter. Model-specific adapters will not be replaced.
Returns:The input adapter.
Return type:Adapter
anom.delete_multi(keys)[source]

Delete a set of entitites from Datastore by their respective keys.

Note

This uses the adapter that is tied to the first model in the list. If the keys have disparate adapters this function may behave in unexpected ways.

Warning

You must pass a list and not a generator or some other kind of iterable to this function as it has to iterate over the list of keys multiple times.

Parameters:keys (list[anom.Key]) – The list of keys whose entities to delete.
Raises:RuntimeError – If the given set of keys have models that use a disparate set of adapters or if any of the keys are partial.
anom.get_multi(keys)[source]

Get a set of entities from Datastore by their respective keys.

Note

This uses the adapter that is tied to the first model in the list. If the keys have disparate adapters this function may behave in unexpected ways.

Warning

You must pass a list and not a generator or some other kind of iterable to this function as it has to iterate over the list of keys multiple times.

Parameters:keys (list[anom.Key]) – The list of keys whose entities to get.
Raises:RuntimeError – If the given set of keys have models that use a disparate set of adapters or if any of the keys are partial.
Returns:Entities that do not exist are going to be None in the result list. The order of results matches the order of the input keys.
Return type:list[Model]
anom.put_multi(entities)[source]

Persist a set of entities to Datastore.

Note

This uses the adapter that is tied to the first Entity in the list. If the entities have disparate adapters this function may behave in unexpected ways.

Warning

You must pass a list and not a generator or some other kind of iterable to this function as it has to iterate over the list of entities multiple times.

Parameters:entities (list[Model]) – The list of entities to persist.
Raises:RuntimeError – If the given set of models use a disparate set of adapters.
Returns:The list of persisted entitites.
Return type:list[Model]
anom.transactional(adapter=None, retries=3, propagation=<Propagation.Nested: 1>)[source]

Decorates functions so that all of their operations (except for queries) run inside a Datastore transaction.

Parameters:
  • adapter (Adapter, optional) – The Adapter to use when running the transaction. Defaults to the current adapter.
  • retries (int, optional) – The number of times to retry the transaction if it couldn’t be committed.
  • propagation (Transaction.Propagation, optional) – The propagation strategy to use. By default, transactions are nested, but you can force certain transactions to always run independently.
Raises:

anom.RetriesExceeded – When the decorator runbs out of retries while trying to commit the transaction.

Returns:

The decorated function.

Return type:

callable

anom.lookup_model_by_kind(kind)[source]

Look up the model instance for a given Datastore kind.

Parameters:kind (str) –
Raises:RuntimeError – If a model for the given kind has not been defined.
Returns:The model class.
Return type:model

Keys

class anom.Key[source]

A Datastore key.

Parameters:
  • kind (str or model) – The Datastore kind this key represents.
  • id_or_name (int or str) – The id or name of this key.
  • parent (anom.Key, optional) – This key’s ancestor.
  • namespace (str, optional) – This key’s namespace.
kind

str – This key’s kind.

id_or_name

int or str or None – This key’s integer id or string name. This is None for partial keys.

parent

anom.Key or None – This key’s ancestor.

namespace

str or None – This key’s namespace.

delete()[source]

Delete the entity represented by this Key from Datastore.

classmethod from_path(*path, namespace=None)[source]

Build up a Datastore key from a path.

Parameters:
  • *path (tuple[str or int]) – The path segments.
  • namespace (str) – An optional namespace for the key. This is applied to each key in the tree.
Returns:

The Datastore represented by the given path.

Return type:

anom.Key

get()[source]

Get the entity represented by this Key from Datastore.

Returns:The entity or None if it does not exist.
Return type:Model
get_model()[source]

Get the model class for this Key.

Raises:RuntimeError – If a model isn’t registered for the Key’s kind.
Returns:A Model class.
Return type:type
int_id

int – This key’s numeric id.

is_partial

boolTrue if this key doesn’t have an id yet.

path

tuple – The full Datastore path represented by this key.

str_id

str – This key’s string id.

Models

class anom.Model(key=None, **properties)[source]

Base class for Datastore models.

key

anom.Key – The Datastore Key for this entity. If the entity was never stored then the Key is going to be partial.

Note

Hooks are only called when dealing with individual entities via their keys. They do not run when entities are loaded from a query.

delete()[source]

Delete this entity from Datastore.

Raises:RuntimeError – If this entity was never stored (i.e. if its key is partial).
classmethod get(id_or_name, *, parent=None, namespace=None)[source]

Get an entity by id.

Parameters:
  • id_or_name (int or str) – The entity’s id.
  • parent (anom.Key, optional) – The entity’s parent Key.
  • namespace (str, optional) – The entity’s namespace.
Returns:

An entity or None if the entity doesn’t exist in Datastore.

Return type:

Model

classmethod post_delete_hook(key)[source]

A hook that runs after an entity has been deleted.

Parameters:key (anom.Key) – The datastore Key of the entity being deleted.
post_get_hook()[source]

A hook that runs after an entity has been loaded from Datastore.

post_put_hook()[source]

A hook that runs after this entity has been persisted.

classmethod pre_delete_hook(key)[source]

A hook that runs before an entity is deleted. Raising an exception here will prevent the entity from being deleted.

Parameters:key (anom.Key) – The datastore Key of the entity being deleted.
classmethod pre_get_hook(key)[source]

A hook that runs before an entity is loaded from Datastore. Raising an exception here will prevent the entity from being loaded.

Parameters:key (anom.Key) – The datastore Key of the entity being loaded.
pre_put_hook()[source]

A hook that runs before this entity is persisted. Raising an exception here will prevent the entity from being persisted.

put()[source]

Persist this entity to Datastore.

classmethod query(**options)[source]

Return a new query for this Model.

Parameters:**options (dict) – Parameters to pass to the Query constructor.
Returns:The new query.
Return type:Query
unindexed_properties

tuple[str] – The names of all the unindexed properties on this entity.

class anom.model.model[source]

Metaclass of Model classes.

Parameters:poly (bool, optional) – Determines if the model should be polymorphic or not. Subclasses of polymorphic models are all stored under the same kind.
_adapter

Adapter – A computed property that returns the adapter for this model class.

_is_child

bool – Whether or not this is a child model in a polymorphic hierarchy.

_is_root

bool – Whether or not this is the root model in a polymorphic hierarchy.

_kind

str – The underlying Datastore kind of this model.

_kinds

list[str] – The list of kinds in this model’s hierarchy.

_properties

dict – A dict of all of the properties defined on this model.

Properties

class anom.Property(name=None, default=None, indexed=False, indexed_if=None, optional=False, repeated=False)[source]

Base class for Datastore model properties.

The property lifecycle is as follows:

  • __init__() is called every time a property is defined on a model class.
  • validate() is called every time a value is assigned to a property on a model instance.
  • prepare_to_load() is called before a property is assigned to a model instance that is being loaded from Datastore.
  • prepare_to_store() is called before a property is persisted from a model instance to Datastore.
Parameters:
  • name (str, optional) – The name of this property on the Datastore entity. Defaults to the name of this property on the model.
  • default (object, optional) – The property’s default value.
  • indexed (bool, optional) – Whether or not this property should be indexed. Defaults to False.
  • indexed_if (callable, optional) – Whether or not this property should be indexed when the callable returns True. Defaults to None.
  • optional (bool, optional) – Whether or not this property is optional. Defaults to False. Required-but-empty values cause models to raise an exception before data is persisted.
  • repeated (bool, optional) – Whether or not this property is repeated. Defaults to False. Optional repeated properties default to an empty list.
is_none

PropertyFilter – A filter that checks if this value is None.

name_on_entity

str – The name of this Property inside the Datastore entity.

name_on_model

str – The name of this Property on the Model instance.

prepare_to_load(entity, value)[source]

Prepare value to be loaded into a Model. Called by the model for each Property, value pair contained in the persisted data when loading it from an adapter.

Parameters:
  • entity (Model) – The entity to which the value belongs.
  • value – The value being loaded.
Returns:

The value that should be assigned to the entity.

prepare_to_store(entity, value)[source]

Prepare value for storage. Called by the Model for each Property, value pair it contains before handing the data off to an adapter.

Parameters:
  • entity (Model) – The entity to which the value belongs.
  • value – The value being stored.
Raises:

RuntimeError – If this property is required but no value was assigned to it.

Returns:

The value that should be persisted.

validate(value)[source]

Validates that value can be assigned to this Property.

Parameters:value – The value to validate.
Raises:TypeError – If the type of the assigned value is invalid.
Returns:The value that should be assigned to the entity.

Property Internals

anom.model.NotFound

Canary value for unset properties.

anom.model.Skip

Canary value for properties that should be skipped when loading entities from Datastore.

Property Mixins

class anom.properties.Blob(**options)[source]

Mixin for Properties whose values cannot be indexed.

class anom.properties.Compressable(compressed=False, compression_level=-1, **options)[source]

Mixin for Properties whose values can be gzipped before being persisted.

Parameters:
  • compressed (bool) – Whether or not values belonging to this Property should be stored gzipped in Datastore.
  • compression_level (int) – The amount of compression to apply. See zlib.compress() for details.
class anom.properties.Encodable(encoding='utf-8', **options)[source]

Mixin for string properties that have an encoding.

Parameters:encoding (str) – The encoding to use when persisting this Property to Datastore. Defaults to utf-8.

Built-in Properties

class anom.properties.Bool(name=None, default=None, indexed=False, indexed_if=None, optional=False, repeated=False)[source]

A Property for boolean values.

Parameters:
  • name (str, optional) – The name of this property on the Datastore entity. Defaults to the name of this property on the model.
  • default (object, optional) – The property’s default value.
  • indexed (bool, optional) – Whether or not this property should be indexed. Defaults to False.
  • indexed_if (callable, optional) – Whether or not this property should be indexed when the callable returns True. Defaults to None.
  • optional (bool, optional) – Whether or not this property is optional. Defaults to False. Required but empty values cause models to raise an exception before data is persisted.
  • repeated (bool, optional) – Whether or not this property is repeated. Defaults to False. Optional repeated properties default to an empty list.
class anom.properties.Bytes(compressed=False, compression_level=-1, **options)[source]

A Property for bytestring values.

Parameters:
  • name (str, optional) – The name of this property on the Datastore entity. Defaults to the name of this property on the model.
  • default (object, optional) – The property’s default value.
  • optional (bool, optional) – Whether or not this property is optional. Defaults to False. Required but empty values cause models to raise an exception before data is persisted.
  • repeated (bool, optional) – Whether or not this property is repeated. Defaults to False. Optional repeated properties default to an empty list.
  • compressed (bool, optional) – Whether or not this property should be compressed before being persisted.
  • compression_level (int, optional) – The amount of compression to apply when compressing values.
class anom.properties.Computed(fn, **options)[source]

A Property for values that should be computed dinamically based on the state of the entity. Values on an entity are only computed the first time computed properties are accessed on that entity and they are re-computed every time the entity is loaded from Datastore.

Computed properties cannot be assigned to and their “cache” can be busted by deleting them:

del an_entity.a_property

Note

Computed properties are indexed and optional by default for convenience. This is different from all other built-in properties.

Parameters:
  • fn (callable) – The function to use when computing the data.
  • name (str, optional) – The name of this property on the Datastore entity. Defaults to the name of this property on the model.
  • default (object, optional) – The property’s default value.
  • indexed (bool, optional) – Whether or not this property should be indexed. Defaults to True.
  • indexed_if (callable, optional) – Whether or not this property should be indexed when the callable returns True. Defaults to None.
  • optional (bool, optional) – Whether or not this property is optional. Defaults to True.
  • repeated (bool, optional) – Whether or not this property is repeated. Defaults to False.
class anom.properties.DateTime(auto_now_add=False, auto_now=False, **options)[source]

A Property for datetime.datetime values.

Parameters:
  • name (str, optional) – The name of this property on the Datastore entity. Defaults to the name of this property on the model.
  • default (object, optional) – The property’s default value.
  • indexed (bool, optional) – Whether or not this property should be indexed. Defaults to False.
  • indexed_if (callable, optional) – Whether or not this property should be indexed when the callable returns True. Defaults to None.
  • optional (bool, optional) – Whether or not this property is optional. Defaults to False. Required but empty values cause models to raise an exception before data is persisted.
  • repeated (bool, optional) – Whether or not this property is repeated. Defaults to False. Optional repeated properties default to an empty list.
  • auto_now_add (bool, optional) – Whether or not to set this property’s value to the current time the first time it’s stored.
  • auto_now (bool, optional) – Whether or not this property’s value should be set to the current time every time it is stored.
class anom.properties.Float(name=None, default=None, indexed=False, indexed_if=None, optional=False, repeated=False)[source]

A Property for floating point values.

Parameters:
  • name (str, optional) – The name of this property on the Datastore entity. Defaults to the name of this property on the model.
  • default (object, optional) – The property’s default value.
  • indexed (bool, optional) – Whether or not this property should be indexed. Defaults to False.
  • indexed_if (callable, optional) – Whether or not this property should be indexed when the callable returns True. Defaults to None.
  • optional (bool, optional) – Whether or not this property is optional. Defaults to False. Required but empty values cause models to raise an exception before data is persisted.
  • repeated (bool, optional) – Whether or not this property is repeated. Defaults to False. Optional repeated properties default to an empty list.
class anom.properties.Integer(name=None, default=None, indexed=False, indexed_if=None, optional=False, repeated=False)[source]

A Property for integer values.

Parameters:
  • name (str, optional) – The name of this property on the Datastore entity. Defaults to the name of this property on the model.
  • default (object, optional) – The property’s default value.
  • indexed (bool, optional) – Whether or not this property should be indexed. Defaults to False.
  • indexed_if (callable, optional) – Whether or not this property should be indexed when the callable returns True. Defaults to None.
  • optional (bool, optional) – Whether or not this property is optional. Defaults to False. Required but empty values cause models to raise an exception before data is persisted.
  • repeated (bool, optional) – Whether or not this property is repeated. Defaults to False. Optional repeated properties default to an empty list.
class anom.properties.Json(compressed=False, compression_level=-1, **options)[source]

A Property for values that should be stored as JSON.

Parameters:
  • name (str, optional) – The name of this property on the Datastore entity. Defaults to the name of this property on the model.
  • default (object, optional) – The property’s default value.
  • optional (bool, optional) – Whether or not this property is optional. Defaults to False. Required but empty values cause models to raise an exception before data is persisted.
  • compressed (bool, optional) – Whether or not this property should be compressed before being persisted.
  • compression_level (int, optional) – The amount of compression to apply when compressing values.
class anom.properties.Key(kind=None, **options)[source]

A Property for anom.Key values.

Parameters:
  • name (str, optional) – The name of this property on the Datastore entity. Defaults to the name of this property on the model.
  • default (object, optional) – The property’s default value.
  • kind (str or model, optional) – The kinds of keys that may be assigned to this property.
  • indexed (bool, optional) – Whether or not this property should be indexed. Defaults to False.
  • indexed_if (callable, optional) – Whether or not this property should be indexed when the callable returns True. Defaults to None.
  • optional (bool, optional) – Whether or not this property is optional. Defaults to False. Required but empty values cause models to raise an exception before data is persisted.
  • repeated (bool, optional) – Whether or not this property is repeated. Defaults to False. Optional repeated properties default to an empty list.
class anom.properties.Msgpack(compressed=False, compression_level=-1, **options)[source]

A Property for values that should be stored as msgpack data.

Parameters:
  • name (str, optional) – The name of this property on the Datastore entity. Defaults to the name of this property on the model.
  • default (object, optional) – The property’s default value.
  • optional (bool, optional) – Whether or not this property is optional. Defaults to False. Required but empty values cause models to raise an exception before data is persisted.
  • compressed (bool, optional) – Whether or not this property should be compressed before being persisted.
  • compression_level (int, optional) – The amount of compression to apply when compressing values.
class anom.properties.String(encoding='utf-8', **options)[source]

A Property for indexable string values.

Parameters:
  • name (str, optional) – The name of this property on the Datastore entity. Defaults to the name of this property on the model.
  • default (object, optional) – The property’s default value.
  • indexed (bool, optional) – Whether or not this property should be indexed. Defaults to False.
  • indexed_if (callable, optional) – Whether or not this property should be indexed when the callable returns True. Defaults to None.
  • optional (bool, optional) – Whether or not this property is optional. Defaults to False. Required but empty values cause models to raise an exception before data is persisted.
  • repeated (bool, optional) – Whether or not this property is repeated. Defaults to False. Optional repeated properties default to an empty list.
  • encoding (str) – The encoding to use when persisting this Property to Datastore. Defaults to utf-8.
class anom.properties.Text(encoding='utf-8', **options)[source]

A Property for long string values that are never indexed.

Parameters:
  • name (str, optional) – The name of this property on the Datastore entity. Defaults to the name of this property on the model.
  • default (object, optional) – The property’s default value.
  • optional (bool, optional) – Whether or not this property is optional. Defaults to False. Required but empty values cause models to raise an exception before data is persisted.
  • repeated (bool, optional) – Whether or not this property is repeated. Defaults to False. Optional repeated properties default to an empty list.
  • compressed (bool, optional) – Whether or not this property should be compressed before being persisted.
  • compression_level (int, optional) – The amount of compression to apply when compressing values.
  • encoding (str) – The encoding to use when persisting this Property to Datastore. Defaults to utf-8.
class anom.properties.Embed(kind, **options)[source]

A property for embedding entities inside other entities.

Parameters:
  • kind (str or model) – The kinds of keys that may be assigned to this property.
  • optional (bool, optional) – Whether or not this property is optional. Defaults to False. Required but empty values cause models to raise an exception before data is persisted.
  • repeated (bool, optional) – Whether or not this property is repeated. Defaults to False. Optional repeated properties default to an empty list.

Built-in Conditions

anom.conditions.is_default(entity, prop, name)[source]

bool: True if the value of a property is equal to its default.

anom.conditions.is_not_default(entity, prop, name)[source]

bool: True if the value of a property is not equal to its default.

anom.conditions.is_empty(entity, prop, name)[source]

bool: True if the value of a property is not set.

anom.conditions.is_not_empty(entity, prop, name)[source]

bool: True if the value of a property is set.

anom.conditions.is_none(entity, prop, name)[source]

bool: True if the value of a property is None.

anom.conditions.is_not_none(entity, prop, name)[source]

bool: True if the value of a property is not None.

anom.conditions.is_true(entity, prop, name)[source]

bool: True if the value of a property is True.

anom.conditions.is_false(entity, prop, name)[source]

bool: True if the value of a property is False.

Queries

class anom.Query[source]

An immutable Datastore query.

Parameters:
  • kind (str or model) – The Datastore kind to query.
  • ancestor (anom.Key, optional) – The ancestor to which this query should be scoped.
  • namespace (str, optional) – The namespace to which this query should be scoped.
  • projection (tuple[str], optional) – The tuple or tuple of fields to project.
  • filters (tuple[PropertyFilter], optional) – The tuple of filters to apply.
  • orders (tuple[str], optional) – The tuple of sort orders to apply.
  • offset (int, optional) – The number of query results to skip.
  • limit (int, optional) – The maximum number of results to return.

Example

You can construct queries declaratively:

people_query = Query(Person)
  .where(Person.email == "test@example.com")
  .and_where(Person.enabled.is_true)
  .with_limit(10)

Then run them to iterate over all the results:

all_people = people_query.run()
for person in all_people:
  print(person)

Or paginate over them:

for page in people_query.paginate(page_size=10):
  print("Cursor: ", page.cursor)
  for person in page:
    print(person)

Or get individual pages of results:

page_1 = people_query.paginate(page_size=10).fetch_next_page()
page_2 = people_query.paginate(page_size=10, cursor=page_1.cursor).fetch_next_page()
and_where(*filters)[source]

Return a new query, adding the given filters with the current query’s filters to form an “and”.

Parameters:*filters (PropertyFilter) – The filters to add.
Returns:The derived Query.
Return type:Query
count(page_size=300, **options)[source]

Counts the number of entities that match this query.

Note

Since Datastore doesn’t provide a native way to count entities by query, this method paginates through all the entities’ keys and counts them.

Parameters:**options (QueryOptions, optional) –
Returns:The number of entities.
Return type:int
delete(page_size=300, **options)[source]

Deletes all the entities that match this query.

Note

Since Datasotre doesn’t provide a native way to delete entities by query, this method paginates through all the entities’ keys and issues a single delete_multi call per page.

Parameters:**options (QueryOptions, optional) –
Returns:The number of deleted entities.
Return type:int
get(**options)[source]

Run this query and get the first result.

Parameters:**options (QueryOptions, optional) –
Returns:An entity or None if there were no results.
Return type:Model
order_by(*orders)[source]

Returns a new query containing an additional set of orders.

Parameters:*orders (str) – The sort orders to add.
Returns:The derived Query.
Return type:Query
paginate(page_size, **options)[source]

Run this query and return a page iterator.

Parameters:
  • page_size (int) – The number of entities to fetch per page.
  • **options (QueryOptions, optional) –
Returns:

An iterator for this query’s pages of results.

Return type:

Pages

run(**options)[source]

Run this query and return a result iterator.

Parameters:**options (QueryOptions, optional) –
Returns:An iterator for this query’s results.
Return type:Resultset
select(*projection)[source]

Return a new query with its projection replaced.

Parameters:*projection (str) – The fields to project.
Returns:The derived Query.
Return type:Query
where(*filters)[source]

Return a new query, replacing the current set of filters.

Parameters:*filters (PropertyFilter) – The filters to add.
Returns:The derived Query.
Return type:Query
with_ancestor(ancestor)[source]

Returns a new query with its ancestor updated.

Parameters:ancestor (anom.Key) – The new ancestor.
Returns:The derived Query.
Return type:Query
with_limit(limit)[source]

Returns a new query with its limit updated.

Parameters:limit (int) – The new limit.
Returns:The derived Query.
Return type:Query
with_namespace(namespace)[source]

Returns a new query with its namespace updated.

Parameters:namespace (str) – The new namespace.
Returns:The derived Query.
Return type:Query
with_offset(offset)[source]

Returns a new query with its offset updated.

Parameters:offset (int) – The new offset.
Returns:The derived Query.
Return type:Query
class anom.Resultset(query, options)[source]

An iterator for datastore query results.

Parameters:
  • query (Query) – The query that was run to create this resultset.
  • options (QueryOptions) – Options that determine how entities are fetched from Datastore.
cursor

str – The url-safe cursor for the next batch of results.

has_more

bool – Whether or not there are more results.

class anom.Pages(query, page_size, options)[source]

An iterator for Pages of results.

Parameters:
  • query (Query) – The query that was run to create this resultset.
  • options (QueryOptions) – Options that determine how entities are fetched from Datastore.
cursor

str – The url-safe cursor for the next page of results.

fetch_next_page()[source]

Fetch the next Page of results.

Returns:The next page of results.
Return type:Page
has_more

bool – Whether or not there are more pages.

class anom.Page(cursor, batch)[source]

An iterator that represents a single page of entities or keys.

Parameters:
  • cursor (str) – The url-safe cursor for the next page of results.
  • batch (iterator[Model or anom.Key]) – The batch of results backing this Page.
cursor

str – The url-safe cursor for the next page of results.

Query Internals

class anom.query.QueryOptions(query, **options)[source]

Options that determine how data is fetched from the Datastore on a per Query basis.

Parameters:
  • batch_size (int, optional) – The number of results to fetch per batch.
  • keys_only (bool, optional) – Whether or not the results should be Keys or Entities.
  • limit (int, optional) – The maximum number of results to return.
  • offset (int, optional) – The number of results to skip.
  • cursor (str, optional) – A url-safe cursor representing where in the result set the query should start.
class anom.query.PropertyFilter[source]

Represents an individual filter on a Property within a Query.

Transactions

class anom.Transaction[source]

Abstract base class for Datastore transactions.

class Propagation[source]

An enum of the various modes transactions can be run in.

Independent = 2

Nested transcations should be run independently of their parent transactions.

Nested = 1

Nested transactions should be grouped together into a single transaction.

begin()[source]

Start this transaction.

commit()[source]

Commit this Transaction to Datastore.

end()[source]

Clean up this Transaction object.

rollback()[source]

Roll this Transaction back.

class anom.transaction.TransactionError[source]

Base class for Transaction errors.

class anom.transaction.TransactionFailed(message, cause=None)[source]

Raised by Adapters when a Transaction cannot be applied.

Parameters:
  • message (str) – A message.
  • cause (Exception or None) – The exception that caused this Transaction to fail.
class anom.transaction.RetriesExceeded(cause)[source]

Raised by the transactional decorator when it runs out of retries while trying to apply a transaction.

Parameters:cause (TransactionError) – The last transaction error that caused a retry.

Adapters

class anom.Adapter[source]

Abstract base class for Datastore adapters. Adapters determine how your Models interact with the Datastore.

current_transaction

Transaction – The current Transaction or None.

delete_multi(keys)[source]

Delete a list of entities from the Datastore by their respective keys.

Parameters:keys (list[anom.Key]) – A list of datastore Keys to delete.
get_multi(keys)[source]

Get multiple entities from the Datastore by their respective keys.

Parameters:keys (list[anom.Key]) – A list of datastore Keys to get.
Returns:A list of dictionaries of data that can be loaded into individual Models. Entries for Keys that cannot be found are going to be None.
Return type:list[dict]
in_transaction

bool – True if the adapter is currently in a Transaction.

put_multi(requests)[source]

Store multiple entities into the Datastore.

Parameters:requests (list[PutRequest]) – A list of datastore requets to persist a set of entities.
Returns:The list of full keys for each stored entity.
Return type:list[anom.Key]
query(query, options)[source]

Run a query against the datastore.

Parameters:
  • query (Query) – The query to run.
  • options (QueryOptions) – Options that determine how the data should be fetched.
Returns:

The query response from Datastore.

Return type:

QueryResponse

transaction(propagation)[source]

Create a new Transaction object.

Parameters:propagation (Transaction.Propagation) – How the new transaction should be propagated with regards to any previously-created transactions.
Returns:The transaction.
Return type:Transaction

Built-in Adapters

class anom.adapters.DatastoreAdapter(project=None, credentials=None)[source]

A Google Cloud Datastore adapter based on google.cloud.datastore.

Parameters:
  • project (str, optional) – The project this Adapter should connect to. Adapter should operate by default. Individual Datastore Keys may specify their own namespaces and override this.
  • credentials (datastore.Credentials) – The OAuth2 Credentials to use for this client. If not passed, falls back to the default inferred from the environment.
current_transaction

Transaction – The current Transaction or None.

delete_multi(keys)[source]

Delete a list of entities from the Datastore by their respective keys.

Parameters:keys (list[anom.Key]) – A list of datastore Keys to delete.
get_multi(keys)[source]

Get multiple entities from the Datastore by their respective keys.

Parameters:keys (list[anom.Key]) – A list of datastore Keys to get.
Returns:A list of dictionaries of data that can be loaded into individual Models. Entries for Keys that cannot be found are going to be None.
Return type:list[dict]
in_transaction

bool – True if the adapter is currently in a Transaction.

put_multi(requests)[source]

Store multiple entities into the Datastore.

Parameters:requests (list[PutRequest]) – A list of datastore requets to persist a set of entities.
Returns:The list of full keys for each stored entity.
Return type:list[anom.Key]
query(query, options)[source]

Run a query against the datastore.

Parameters:
  • query (Query) – The query to run.
  • options (QueryOptions) – Options that determine how the data should be fetched.
Returns:

The query response from Datastore.

Return type:

QueryResponse

transaction(propagation)[source]

Create a new Transaction object.

Parameters:propagation (Transaction.Propagation) – How the new transaction should be propagated with regards to any previously-created transactions.
Returns:The transaction.
Return type:Transaction
class anom.adapters.MemcacheAdapter(client, adapter, *, prefix='anom')[source]

Transparently adds memcached-based strongly-consistent caching on top of another adapter for delete, get and put operations.

Parameters:
  • client (pylibmc.Client) – The memcached client instance to use. This is automatically wrapped inside a ThreadMappedPool.
  • adapter (Adapter) – The adapter to wrap.
  • prefix (str, optional) – The string keys should be prefixed with. Defaults to anom.
current_transaction

Transaction – The current Transaction or None.

delete_multi(keys)[source]

Delete a list of entities from the Datastore by their respective keys.

Parameters:keys (list[anom.Key]) – A list of datastore Keys to delete.
get_multi(keys)[source]

Get multiple entities from the Datastore by their respective keys.

Parameters:keys (list[anom.Key]) – A list of datastore Keys to get.
Returns:A list of dictionaries of data that can be loaded into individual Models. Entries for Keys that cannot be found are going to be None.
Return type:list[dict]
in_transaction

bool – True if the adapter is currently in a Transaction.

put_multi(requests)[source]

Store multiple entities into the Datastore.

Parameters:requests (list[PutRequest]) – A list of datastore requets to persist a set of entities.
Returns:The list of full keys for each stored entity.
Return type:list[anom.Key]
transaction(propagation)[source]

Create a new Transaction object.

Parameters:propagation (Transaction.Propagation) – How the new transaction should be propagated with regards to any previously-created transactions.
Returns:The transaction.
Return type:Transaction

Adapter Internals

class anom.adapter.PutRequest[source]

Represents requests to persist individual Models.

Parameters:
  • key (anom.Key) – A datastore Key.
  • unindexed (list[str]) – A list of properties that should not be indexed.
  • properties (iter[tuple[str, Property]]) – An iterable representing the properties that should be stored by this put.
class anom.adapter.QueryResponse[source]

Represents query responses from Datastore.

Parameters:
  • entities (list[tuple[anom.Key, dict]]) – The list of results.
  • cursor (str) – The cursor that points to the next page of results. This value must be url-safe.

Testing

class anom.testing.Emulator(host='127.0.0.1', port=9898, consistency=1)[source]

Runs the Cloud Datastore emulator in a subprocess for testing purposes.

Parameters:
  • host (str) – The host name the emulator should bind to.
  • port (int) – The port on which the emulator should listen on.
  • consistency (float) – A value between 0.0 and 1.0 representing the percentage of datastore requests that should succeed.

Example:

from anom.testing import Emulator

@pytest.fixture(scope="session")
def emulator():
  emulator = Emulator()
  emulator.start(inject=True)
  yield
  emulator.stop()
start(timeout=15, inject=False)[source]

Start the emulator process and wait for it to initialize.

Parameters:
  • timeout (int) – The maximum number of seconds to wait for the Emulator to start up.
  • inject (bool) – Whether or not to inject the emulator env vars into the current process.
Returns:

A dictionary of env vars that can be used to access the Datastore emulator.

Return type:

dict

stop()[source]

Stop the emulator process.

Returns:The process return code or None if the process isn’t currently running.
Return type:int