API Docs

Tasty loaves of bread.

bread.model module

Bread model.

class bread.model.BaseModel[source]

Bases: type

Generates a new class from field definitions.

The class will have a property on it called _fields that will contain any model properties that were found.

class bread.model.BasePolyModel[source]

Bases: bread.model.BaseModel

Like a model but all instances of such a model get stored under the same collection, which defaults to the collection belonging to the root PolyModel.

class bread.model.Model(**kwargs)[source]

Bases: object

Banana models group Banana properties.

To utilize the access control helpers, create two model fields, allowed_role and allowed_groups, to indicate the minimum role level (as an int) and the minimum group membership (as a string, checked for membership in a group list).

classmethod class_delete(keys, soft=True, dataset=None, collection=None, _async=False, **kwargs)[source]

Delete an entity or a list of entities.

Examples:
>>> Person.delete("a")
>>> Person.delete(Key(Person, "a"))
>>> Person.delete([Key(Person, "a"), Key(Person, "b")])
>>> Person.delete([Key(Person, "a"), Key(Person, "b")], soft=False)
Note:

Class deletes operate over the default collection and dataset for the current model.

Parameters:
  • str, Key keys (list,) – A UUID, a Key or a list of UUIDs or Keys.
  • soft (bool) – Whether or not to soft-delete the entities.
  • dataset (str) –
  • collection (str) –
  • _async (bool) –
classmethod class_delete_async(keys, soft=True, dataset=None, collection=None)[source]

Asynchronous variant of class_delete().

classmethod class_get(keys, dataset=None, collection=None, role=None, groups=None, deleted=False)[source]

Get an entity or a list of entities. Validates role and groups if given.

Examples:
>>> Person.get("a")
Person(...)
>>> Person.get("b")
None
>>> Person.get(Key(Person, "a"))
Person(...)
>>> Person.get(["a", Key(Person, "a"), "b"])
[Person(...), Person(...), None]
>>> Person.get("a", role=user.role, groups=user.groups)
Person(...)
Note:

By default, class gets operate over the default collection and dataset for the current model.

Parameters:
  • str, Key keys (list,) – A UUID, a Key or a list of UUIDs or Keys.
  • dataset (str) –
  • collection (str) –
  • role (int) – Role to fetch with.
  • groups (list) – List of groups or single group as str to fetch with.
  • deleted (bool) – Whether or not to return soft-deleted results. Defaults to False.
Returns:

One of: an entity, a list of entities or None. For multi get operations the resulting list will always have the same length as the key list.

classmethod class_get_async(keys, dataset=None, collection=None, role=None, groups=None, deleted=False)[source]

Asynchronous variant of class_get().

classmethod class_save(entities, dataset=None, collection=None, _async=False, updated=True, **kwargs)[source]

Save an entity or a list of entities.

Examples:
>>> Person.save(Person())
>>> Person.save([Person(name="Scott"), Person(name="Jean")])
>>> Person.save([Person.get("a")])
Parameters:
  • Model entities (list,) –
  • dataset (str) –
  • collection (str) –
  • _async (bool) –
Returns:

A list representing the saved Entities.

classmethod class_save_async(entities, dataset=None, collection=None, updated=True)[source]

Asynchronous variant of class_save().

delete(keys, soft=True, dataset=None, collection=None, _async=False, **kwargs)

Delete an entity or a list of entities.

Examples:
>>> Person.delete("a")
>>> Person.delete(Key(Person, "a"))
>>> Person.delete([Key(Person, "a"), Key(Person, "b")])
>>> Person.delete([Key(Person, "a"), Key(Person, "b")], soft=False)
Note:

Class deletes operate over the default collection and dataset for the current model.

Parameters:
  • str, Key keys (list,) – A UUID, a Key or a list of UUIDs or Keys.
  • soft (bool) – Whether or not to soft-delete the entities.
  • dataset (str) –
  • collection (str) –
  • _async (bool) –
delete_async(keys, soft=True, dataset=None, collection=None)

Asynchronous variant of class_delete().

dump()[source]
classmethod fetch(query=None, order=None, limit=10, cursor=None, role=0, groups=None, deleted=False, dataset=None, collection=None, _async=False, **kwargs)[source]

Query for entities.

The query argument is either a tuple or a list of tuples, where each tuple is a trio of (property, op, value), for example: ("n", ">", 10).

Valid op values are >=, <, >, <=, =, != and in.

The order argument is either a tuple or a list of tuples, where each tuple is a pair of (property, direction), for example: ("n", "desc").

Valid direction values are asc and desc.

Note:

If the more value is None, the value is unsupported.

Parameters:
  • query (tuple) – A query tuple (or list of query tuples).
  • order (tuple) – A sorting order tuple (or list of sorting order tuples).
  • limit (int) – Number of results to return.
  • cursor (str) – Cursor to use in query.
  • role (int) – Role to use in query.
  • groups (list) – Groups to use in query.
  • deleted (bool) – Whether or not to include soft-deleted entities in the query.
  • collection (str) – The collection inside which to run the query.
  • _async (bool) – Whether or not the query should be performed asynchronously.
Returns:

Tuple of Model entities, str cursor, and bool more. If _async is True the tuple is wrapped in a Future.

get(keys, dataset=None, collection=None, role=None, groups=None, deleted=False)

Get an entity or a list of entities. Validates role and groups if given.

Examples:
>>> Person.get("a")
Person(...)
>>> Person.get("b")
None
>>> Person.get(Key(Person, "a"))
Person(...)
>>> Person.get(["a", Key(Person, "a"), "b"])
[Person(...), Person(...), None]
>>> Person.get("a", role=user.role, groups=user.groups)
Person(...)
Note:

By default, class gets operate over the default collection and dataset for the current model.

Parameters:
  • str, Key keys (list,) – A UUID, a Key or a list of UUIDs or Keys.
  • dataset (str) –
  • collection (str) –
  • role (int) – Role to fetch with.
  • groups (list) – List of groups or single group as str to fetch with.
  • deleted (bool) – Whether or not to return soft-deleted results. Defaults to False.
Returns:

One of: an entity, a list of entities or None. For multi get operations the resulting list will always have the same length as the key list.

get_async(keys, dataset=None, collection=None, role=None, groups=None, deleted=False)

Asynchronous variant of class_get().

instance_delete(soft=True)[source]

Clear the model and delete the entity from backend.

Parameters:soft (bool) – Whether or not to soft-delete the entity.
instance_delete_async(soft=True)[source]

Asynchronous variant of instance_delete().

instance_get()[source]

Reinitialize the model from backend.

Returns:A bool representing whether or not loading the model succeeded.
instance_get_async()[source]

Asynchronous variant of instance_get().

instance_save(updated=True)[source]

Serialize entity and save to backend.

instance_save_async(updated=True)[source]

Asynchronous variant of instance_save().

key
load(data)[source]
classmethod query(*filters, **params)[source]

Query for entities.

Parameters:
  • filters – The initial list of queries.
  • limit (str) – The initial limit.
  • limit – The initial cursor.
  • role (int) – The initial role.
  • groups (list) – The initial groups.
  • deleted (bool) – The initial inclusion of soft-deleted entities.
  • dataset (str) – The initial dataset.
  • collection (str) – The initial collection.
Returns:

A Query object.

save(entities, dataset=None, collection=None, _async=False, updated=True, **kwargs)

Save an entity or a list of entities.

Examples:
>>> Person.save(Person())
>>> Person.save([Person(name="Scott"), Person(name="Jean")])
>>> Person.save([Person.get("a")])
Parameters:
  • Model entities (list,) –
  • dataset (str) –
  • collection (str) –
  • _async (bool) –
Returns:

A list representing the saved Entities.

save_async(entities, dataset=None, collection=None, updated=True)

Asynchronous variant of class_save().

class bread.model.PolyModel(**kwargs)[source]

Bases: bread.model.Model

classmethod fetch(query=None, order=None, limit=10, cursor=None, role=0, groups=None, deleted=False, dataset=None, collection=None, _async=False, **kwargs)[source]

Query for entities. This is the same as Model.fetch() with two exceptions:

  1. Queries on root PolyModels instantiate individual entities to their respective models.
  2. Queries on non-root PolyModels limit the resultset to entities matching that Model.

Submodules

bread.backend module

This module contains abstract representations for Backends and Transactions as well as global state for keeping track of the current backend.

class bread.backend.Backend[source]

Bases: object

Abstract storage backend with ORM-layer concrete helpers.

begin()[source]

Create a new BackendTransaction instance specific to the current backend.

collection
dataset
delete(keys, dataset=None, collection=None)[source]

Delete a set of Entities by their Keys.

Parameters:
  • keys (list) –
  • dataset (str) –
  • collection (str) –
delete_async(keys, dataset=None, collection=None)[source]

Asynchronous variant of delete().

Returns:A Future representing the async computation.
executor
fetch(of_type, query, order, limit, cursor, dataset=None, collection=None)[source]

Query entities.

Backends must support queries where the query is a list of tuples, and where each tuple is a trio of (property, op, value), for example, [("n", ">", 10)] or [("n", ">", 10), ("x", "=", "alpha")].

Valid op values are >=, <, >, <=, =, != and in.

Backends must support sort orders where the sort order is a list of tuples, and where each tuple is a pair of (property, direction), for example: [("n", "desc")].

Valid direction values are asc and desc.

The backend must construct and return Key instances for each returned entity. Each serialized entity will be expected to have a dictionary index key with a Key instance as the value. This is required so that we do not have to know which underlying field the backend considers the “ID”.

Parameters:
  • of_type (str) – Entity type to query for.
  • query (tuple) – List of tuples representing a query.
  • order (tuple) – List of tuples representing a sorting order.
  • limit (int) – Positive integer reresenting the maximum number of entities to return.
  • cursor (str) – Opaque value representing a position in the query result set.
Returns:

Tuple of (entities, cursor, more) where entities is a list of entities in their serialized form that they were saved as, cursor is an opaque string representing a position in the query result set, and more is a boolean representing whether or not a subsequent query, passing in the returned cursor, would produce more results.

fetch_async(of_type, query, order, limit, cursor, dataset=None, collection=None)[source]

Asynchronous variant of fetch().

Returns:A future representing the result tuple.
get(keys, dataset=None, collection=None)[source]

Get a list of Entities by their Keys.

Parameters:
  • keys (list) –
  • dataset (str) –
  • collection (str) –
Returns:

A list of Entities.

get_async(keys, dataset=None, collection=None)[source]

Asynchronous variant of get().

Returns:A Future representing a list of Entities.
local_policy(**kwds)[source]

Customize this Backend’s behavoir within a “with” block.

Examples:
>>> with bread.get_backend().local_policy(skip_cache=True):
...   Model.query().run()
max_workers
policy
policy_class
reauthorize()[source]

Reauthorize the underlying connection for this backend. The default implementation is a no-op.

save(keys, data, meta=None, dataset=None, collection=None)[source]

Save a list of entities by Key.

Parameters:
  • keys (list) –
  • data (list) –
  • meta (list) –
  • dataset (str) –
  • collection (str) –
Returns:

A list representing the saved Entities.

save_async(keys, data, meta=None, dataset=None, collection=None)[source]

Asynchronous variant of save().

Returns:A Future representing a list of the saved Entities.
set_default_policy(**kwargs)[source]
class bread.backend.BackendTransaction[source]

Bases: object

Base class for representing an abstract database transaction.

collection
commit()[source]
dataset
delete(key)[source]
rollback()[source]
save(key, serialized, meta=None)[source]
class bread.backend.Policy[source]

Bases: object

Policies control the runtime behavior of Backends. Backends may or may not expose policies.

classmethod build()[source]
bread.backend.get_backend()[source]
bread.backend.set_backend(new_backend=None, dataset=None, collection=None, model_name_prefix=None, max_workers=None)[source]

bread.errors module

exception bread.errors.BackendLookupError(message)[source]

Bases: bread.errors.BreadError

Raised if data lookup fails when it should have succeeded. Eg. this fails if the Cloud Datastore backup fails to return non-deferred results on a key get.

exception bread.errors.BreadError(message)[source]

Bases: exceptions.Exception

All bread errors extend this class.

exception bread.errors.RetriesExceeded(error)[source]

Bases: bread.errors.BreadError

Raised when an underlying operation was retried too many times.

bread.key module

Bread keys.

class bread.key.Key(of_type, uuid)[source]

Bases: object

An identifier for the entity. Proxies get model method.

get()[source]

Fetch an entity by key.

get_async()[source]

Fetch an entity asynchronously by key.

of_type
bread.key.import_lazy_model(of)[source]

bread.properties module

This module contains definitions for the available Bread property types as well their ABC.

class bread.properties.BaseProperty(default=None, index=True, required=False)[source]

Bases: object

is_in(other)[source]
class bread.properties.BooleanProperty(default=None, index=True, required=False)[source]

Bases: bread.properties.BaseProperty

class bread.properties.ComputedProperty(f, **kwargs)[source]

Bases: bread.properties.BaseProperty

Properties that compute their value based on the state of the Entity.

Examples:

>>> class Foo(bread.Model):
...   x = bread.IntegerProperty()
...   # XXX: We didn't give x a default value so it could be None.
...   double_x = bread.ComputedProperty(lambda s: s.x * 2 if s.x else 0)
>>> f = Foo()
>>> f.x = 42
>>> f.double_x
84
>>> f.save()
>>> Foo.query(Foo.double_x == 84).run().entites == [f]
True
class bread.properties.DateTimeProperty(default=None, index=True, required=False)[source]

Bases: bread.properties.BaseProperty

DateTime property.

datetime values are converted to local time and then to UTC timestamps on assignment. Timezone-unaware objects are assumed to be in local time. Subsequent accesses always return datetime instances in UTC.

Note:
Microsecond information is lost during conversion.
class bread.properties.FloatProperty(default=None, index=True, required=False)[source]

Bases: bread.properties.BaseProperty

class bread.properties.IntegerProperty(default=None, index=True, required=False)[source]

Bases: bread.properties.BaseProperty

class bread.properties.JsonProperty(json_default=None, json_separators=(', ', ':'), compress=False, level=3, **kwargs)[source]

Bases: bread.properties.BaseProperty

class bread.properties.KeyProperty(of=None, **kwargs)[source]

Bases: bread.properties.BaseProperty

model
class bread.properties.ListProperty(of=<type 'unicode'>, default=None, **kwargs)[source]

Bases: bread.properties.BaseProperty

bread.properties.Missing = <object object>

Canary value used to identify missing field data.

class bread.properties.StringProperty(choices=None, encoding='utf-8', **kwargs)[source]

Bases: bread.properties.BaseProperty

String property.

Strings are always encoded to byte strings on assignment based on the :prop:`.encoding`. These byte strings are what gets persisted to disk. When you access the value of a stored string, it will always be given back to you under the correct encoding. If you want to store arbitray byte strings with no encoding you may use None as the encoding, note that you will always have to ensure that the values you assign to this property as str values if you use an encoding of None.

Essentially these properties offer the following guarantees: - if you assign them a unicode object, it will be

converted to a byte string according to :prop:`.encoding` and that byte string will be persisted to disk.
  • if you assign them a str object, that string will be converted to a unicode object according to :prop:`.encoding` and then back to a byte string and that byte string will be persisted to disk.
  • if an encoding is set, you will always get a value back under that encoding when reading a property.
Parameters:
  • default (six.string_types) – The default value of this property.
  • encoding (str) – The encoding that values boxed by this property. Defaults to utf-8.
bread.properties.seconds_since_epoch(dt)[source]

bread.query module

class bread.query.Iterator(rs)[source]

Bases: object

next()[source]
class bread.query.Query(model, limit, cursor, orders, role, groups, deleted, dataset, collection, *filters)[source]

Bases: object

Provides useful combinators for building up and running queries on Models.

collection

Accessor for the groups.

copy(model=None, limit=None, cursor=None, orders=None, filters=None, role=None, groups=None, deleted=None, dataset=None, collection=None)[source]

Create a copy of this instance overriding any of the arguments.

Parameters:
  • model – An override for the underlying model.
  • limit (int) – An override for the limit.
  • cursor (str) – An override for the cursor.
  • orders (list) – An override for the sort orders.
  • filters (list) – An override for the filters.
  • role (int) – An override for the role.
  • deleted (bool) – An override for including deleted entities.
  • groups (list) – An override for the groups.
  • dataset (str) – An override for the dataset.
  • collection (str) – An override for the collection.
Returns:

A copy of this instance.

cursor

Accessor for the cursor.

dataset

Accessor for the groups.

deleted

Accessor for soft delete setting.

filters

Accessor for the filters.

get()[source]

Run this query and return the first result.

Returns:A model instance or None if there were no results.
groups

Accessor for the groups.

limit

Accessor for the limit.

model

Accessor for the underlying model.

order_by(*orders)[source]

Generates a new instance of this Query with the added orders.

See model.Model.fetch() for more information.

Parameters:orders – A variable list of query sort orders.
Returns:A new Query.
orders

Accessor for the orders.

role

Accessor for the role.

run(_async=False, **kwargs)[source]

Run this Query on the underlying model.

See model.Model.fetch() for more information.

Warning:Queries with multiple IN filters may deadlock if run asynchronously.
Parameters:_async (bool) – Whether or not the Query should be run asynchronously.
Returns:A ResultSet.
where(*filters)[source]

Generates a new instance of this Query with the added filters.

See model.Model.fetch() for more information.

Parameters:filters – A variable list of query filters.
Returns:A new Query.
with_collection(collection)[source]

Generates a new instance of this Query with its collection set to collection.

Parameters:collection (str) – The collection in which to query.
Returns:A new Query.
with_cursor(cursor)[source]

Generates a new instance of this Query with its cursor set to cursor.

Parameters:cursor – The new cursor.
Returns:A new Query.
with_dataset(dataset)[source]

Generates a new instance of this Query with its dataset set to dataset.

Parameters:dataset (str) – The dataset in which to query.
Returns:A new Query.
with_deleted(deleted)[source]

Generates a new instance of this Query with its deleted set to deleted.

Parameters:deleted (str) – Whether or not to include deleted entities.
Returns:A new Query.
with_identity(role, groups)[source]

Generates a new instance of this Query with its role and groups set to role and groups, respectively.

Parameters:
  • role – The active role to query with.
  • groups – The active groups to query with.
Returns:

A new Query.

with_limit(limit)[source]

Generate a new instance of this Query with its limit set to limit.

Parameters:limit (int) – The new limit.
Returns:A new Query.
class bread.query.ResultSet[source]

Bases: bread.query.ResultSet

all_entities

Lazily retrieve all the subsequent pages of results starting with the current ResultSet. Pages are retrieved in batches of the initial Query’s limit.

next_page

Return a Query representing the next page of results.

bread.transaction module

class bread.transaction.Transaction[source]

Bases: object

Transactions group operations together for isolation.

begin(retries=0)[source]
commit()[source]
delete(key)[source]
get(key)[source]
rollback()[source]
save(entity)[source]
exception bread.transaction.TransactionError(error=None)[source]

Bases: bread.errors.BreadError

Base class for transaction errors.

exception bread.transaction.TransactionFailure(error=None)[source]

Bases: bread.transaction.TransactionError

Raised when a Transaction failed but is safe to retry.

bread.transaction.transactional(max_retries=3, max_backoff=5.0)[source]

A decorator that automatically retries failed Transactions.

Parameters:
max_retries (int): The maximum number of times the function
should be retried.
max_backoff (float): The cutoff for the exponential backoff
function.
Note:
The Transaction instance passed in as the final _positional_ argument of the wrapped function or method.
Example:
class Account(bread.Model):

balance = bread.IntegerProperty()

@bread.transactional(max_retries=10) def transfer_funds(self, target_key, amount, transaction):

a, b = Account.get([self.key, target_key]) a.balance -= amount b.balance += amount transaction.save(a) transaction.save(b)