API Docs¶
Tasty loaves of bread.
bread.model module¶
Bread model.
-
class
bread.model.BaseModel[source]¶ Bases:
typeGenerates 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.BaseModelLike 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:
objectBanana 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
Keyor a list of UUIDs or Keys. - soft (bool) – Whether or not to soft-delete the entities.
- dataset (str) –
- collection (str) –
- _async (bool) –
- str, Key keys (list,) – A UUID, a
-
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
Keyor 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.
- str, Key keys (list,) – A UUID, a
-
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
Keyor a list of UUIDs or Keys. - soft (bool) – Whether or not to soft-delete the entities.
- dataset (str) –
- collection (str) –
- _async (bool) –
- str, Key keys (list,) – A UUID, a
-
delete_async(keys, soft=True, dataset=None, collection=None)¶ Asynchronous variant of
class_delete().
-
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
queryargument 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
>=,<,>,<=,=,!=andin.The
orderargument 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
ascanddesc.Note: If the
morevalue isNone, 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
Modelentities, strcursor, and boolmore. If _async isTruethe 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
Keyor 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.
- str, Key keys (list,) – A UUID, a
-
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_async(updated=True)[source]¶ Asynchronous variant of
instance_save().
-
key¶
-
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
Queryobject.
-
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().
-
classmethod
-
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:- Queries on root
PolyModelsinstantiate individual entities to their respective models. - Queries on non-root
PolyModelslimit the resultset to entities matching thatModel.
- Queries on root
-
classmethod
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:
objectAbstract storage backend with ORM-layer concrete helpers.
-
begin()[source]¶ Create a new
BackendTransactioninstance 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
>=,<,>,<=,=,!=andin.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
ascanddesc.The backend must construct and return
Keyinstances for each returned entity. Each serialized entity will be expected to have a dictionary index key with aKeyinstance 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
entitiesis a list of entities in their serialized form that they were saved as,cursoris an opaque string representing a position in the query result set, andmoreis 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 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.
-
-
class
bread.backend.BackendTransaction[source]¶ Bases:
objectBase class for representing an abstract database transaction.
-
collection¶
-
dataset¶
-
bread.errors module¶
-
exception
bread.errors.BackendLookupError(message)[source]¶ Bases:
bread.errors.BreadErrorRaised 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.ExceptionAll bread errors extend this class.
-
exception
bread.errors.RetriesExceeded(error)[source]¶ Bases:
bread.errors.BreadErrorRaised when an underlying operation was retried too many times.
bread.key module¶
Bread keys.
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
-
class
bread.properties.ComputedProperty(f, **kwargs)[source]¶ Bases:
bread.properties.BasePropertyProperties 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.BasePropertyDateTime 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.JsonProperty(json_default=None, json_separators=(', ', ':'), compress=False, level=3, **kwargs)[source]¶
-
class
bread.properties.KeyProperty(of=None, **kwargs)[source]¶ Bases:
bread.properties.BaseProperty-
model¶
-
-
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.BasePropertyString 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
strvalues if you use an encoding ofNone.Essentially these properties offer the following guarantees: - if you assign them a
unicodeobject, it will beconverted to a byte string according to :prop:`.encoding` and that byte string will be persisted to disk.- if you assign them a
strobject, 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.
- if you assign them a
bread.query module¶
-
class
bread.query.Query(model, limit, cursor, orders, role, groups, deleted, dataset, collection, *filters)[source]¶ Bases:
objectProvides 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
Querywith the addedorders.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
Queryon 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
Querywith the addedfilters.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
Querywith its collection set tocollection.Parameters: collection (str) – The collection in which to query. Returns: A new Query.
-
with_cursor(cursor)[source]¶ Generates a new instance of this
Querywith its cursor set tocursor.Parameters: cursor – The new cursor. Returns: A new Query.
-
with_dataset(dataset)[source]¶ Generates a new instance of this
Querywith its dataset set todataset.Parameters: dataset (str) – The dataset in which to query. Returns: A new Query.
-
with_deleted(deleted)[source]¶ Generates a new instance of this
Querywith its deleted set todeleted.Parameters: deleted (str) – Whether or not to include deleted entities. 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:
objectTransactions group operations together for isolation.
-
exception
bread.transaction.TransactionError(error=None)[source]¶ Bases:
bread.errors.BreadErrorBase class for transaction errors.
-
exception
bread.transaction.TransactionFailure(error=None)[source]¶ Bases:
bread.transaction.TransactionErrorRaised 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)