desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Apply a function to the property value/values of a given entity. This retrieves the property value, applies the function, and then stores the value back. For a repeated property, the function is applied separately to each of the values in the list. The resulting value or list of values is both stored back in the ent...
def _apply_to_values(self, entity, function):
value = self._retrieve_value(entity, self._default) if self._repeated: if (value is None): value = [] self._store_value(entity, value) else: value[:] = map(function, value) elif (value is not None): newvalue = function(value) if ((newvalue ...
'Internal helper to get the value for this Property from an entity. For a repeated Property this initializes the value to an empty list if it is not set.'
def _get_value(self, entity):
if entity._projection: if (self._name not in entity._projection): raise UnprojectedPropertyError(('Property %s is not in the projection' % (self._name,))) return self._get_user_value(entity)
'Internal helper to delete the value for this Property from an entity. Note that if no value exists this is a no-op; deleted values will not be serialized but requesting their value will return None (or an empty list in the case of a repeated Property).'
def _delete_value(self, entity):
if (self._name in entity._values): del entity._values[self._name]
'Internal helper to ask if the entity has a value for this Property. This returns False if a value is stored but it is None.'
def _is_initialized(self, entity):
return ((not self._required) or ((self._has_value(entity) or (self._default is not None)) and (self._get_value(entity) is not None)))
'Descriptor protocol: get the value from the entity.'
def __get__(self, entity, unused_cls=None):
if (entity is None): return self return self._get_value(entity)
'Descriptor protocol: set the value on the entity.'
def __set__(self, entity, value):
self._set_value(entity, value)
'Descriptor protocol: delete the value from the entity.'
def __delete__(self, entity):
self._delete_value(entity)
'Internal helper to serialize this property to a protocol buffer. Subclasses may override this method. Args: entity: The entity, a Model (subclass) instance. pb: The protocol buffer, an EntityProto instance. prefix: Optional name prefix used for StructuredProperty (if present, must end in \'.\'). parent_repeated: True ...
def _serialize(self, entity, pb, prefix='', parent_repeated=False, projection=None):
values = self._get_base_value_unwrapped_as_list(entity) for val in values: name = (prefix + self._name) if (projection and (name not in projection)): continue if self._indexed: p = pb.add_property() else: p = pb.add_raw_property() p.set...
'Internal helper to deserialize this property from a protocol buffer. Subclasses may override this method. Args: entity: The entity, a Model (subclass) instance. p: A Property Message object (a protocol buffer). depth: Optional nesting depth, default 1 (unused here, but used by some subclasses that override this method...
def _deserialize(self, entity, p, unused_depth=1):
v = p.value() val = self._db_get_value(v, p) if (val is not None): val = _BaseValue(val) if self._repeated: if self._has_value(entity): value = self._retrieve_value(entity) assert isinstance(value, list), repr(value) value.append(val) else: ...
'Internal helper to check this property for specific requirements. Called by Model._check_properties(). Args: rest: Optional subproperty to check, of the form \'name1.name2...nameN\'. Raises: InvalidPropertyError if this property does not meet the given requirements or if a subproperty is specified. (StructuredPropert...
def _check_property(self, rest=None, require_indexed=True):
if (require_indexed and (not self._indexed)): raise InvalidPropertyError(('Property is unindexed %s' % self._name)) if rest: raise InvalidPropertyError(('Referencing subproperty %s.%s but %s is not a structured property' % (self._name, rest, self._name)))
'Retrieve the value like _get_value(), processed for _to_dict(). Property subclasses can override this if they want the dictionary returned by entity._to_dict() to contain a different value. The main use case is StructuredProperty and LocalStructuredProperty. NOTES: - If you override _get_for_dict() to return a differ...
def _get_for_dict(self, entity):
return self._get_value(entity)
'Setter for key attribute.'
def _set_value(self, entity, value):
if (value is not None): value = _validate_key(value, entity=entity) value = entity._validate_key(value) entity._entity_key = value
'Getter for key attribute.'
def _get_value(self, entity):
return entity._entity_key
'Deleter for key attribute.'
def _delete_value(self, entity):
entity._entity_key = None
'Constructor. Argument is a string returned by zlib.compress().'
def __init__(self, z_val):
assert isinstance(z_val, str), repr(z_val) self.z_val = z_val
'Override _get_value() to *not* raise UnprojectedPropertyError.'
def _get_value(self, entity):
value = self._get_user_value(entity) if ((value is None) and entity._projection): return super(StructuredProperty, self)._get_value(entity) return value
'Dynamically get a subproperty.'
def __getattr__(self, attrname):
prop = self._modelclass._properties.get(attrname) if ((prop is None) or (prop._code_name != attrname)): for prop in self._modelclass._properties.values(): if (prop._code_name == attrname): break else: prop = None if (prop is None): raise Attrib...
'Override for Property._check_property(). Raises: InvalidPropertyError if no subproperty is specified or if something is wrong with the subproperty.'
def _check_property(self, rest=None, require_indexed=True):
if (not rest): raise InvalidPropertyError(('Structured property %s requires a subproperty' % self._name)) self._modelclass._check_properties([rest], require_indexed=require_indexed)
'Constructor. Args: func: A function that takes one argument, the model instance, and returns a calculated value.'
def __init__(self, func, name=None, indexed=None, repeated=None, verbose_name=None):
super(ComputedProperty, self).__init__(name=name, indexed=indexed, repeated=repeated, verbose_name=verbose_name) self._func = func
'Creates a new instance of this model (a.k.a. an entity). The new entity must be written to the datastore using an explicit call to .put(). Keyword Args: key: Key instance for this model. If key is used, id and parent must be None. id: Key id for this model. If id is used, key must be None. parent: Key instance for the...
def __init__(*args, **kwds):
if (len(args) > 1): raise TypeError('Model constructor takes no positional arguments.') (self,) = args get_arg = self.__get_arg key = get_arg(kwds, 'key') id = get_arg(kwds, 'id') app = get_arg(kwds, 'app') namespace = get_arg(kwds, 'namespace') parent = get_arg(kw...
'Internal helper method to parse keywords that may be property names.'
@classmethod def __get_arg(cls, kwds, kwd):
alt_kwd = ('_' + kwd) if (alt_kwd in kwds): return kwds.pop(alt_kwd) if (kwd in kwds): obj = getattr(cls, kwd, None) if ((not isinstance(obj, Property)) or isinstance(obj, ModelKey)): return kwds.pop(kwd) return None
'Populate an instance from keyword arguments. Each keyword argument will be used to set a corresponding property. Keywords must refer to valid property name. This is similar to passing keyword arguments to the Model constructor, except that no provisions for key, id or parent are made.'
def _populate(self, **kwds):
self._set_attributes(kwds)
'Internal helper to set attributes from keyword arguments. Expando overrides this.'
def _set_attributes(self, kwds):
cls = self.__class__ for (name, value) in kwds.iteritems(): prop = getattr(cls, name) if (not isinstance(prop, Property)): raise TypeError(('Cannot set non-property %s' % name)) prop._set_value(self, value)
'Internal helper to find uninitialized properties. Returns: A set of property names.'
def _find_uninitialized(self):
return set((name for (name, prop) in self._properties.iteritems() if (not prop._is_initialized(self))))
'Internal helper to check for uninitialized properties. Raises: BadValueError if it finds any.'
def _check_initialized(self):
baddies = self._find_uninitialized() if baddies: raise datastore_errors.BadValueError(('Entity has uninitialized properties: %s' % ', '.join(baddies)))
'Return an unambiguous string representation of an entity.'
def __repr__(self):
args = [] for prop in self._properties.itervalues(): if prop._has_value(self): val = prop._retrieve_value(self) if (val is None): rep = 'None' elif prop._repeated: reprs = [prop._value_to_repr(v) for v in val] if reprs: ...
'Return the kind name for this class. This defaults to cls.__name__; users may overrid this to give a class a different on-disk name than its class name.'
@classmethod def _get_kind(cls):
return cls.__name__
'A hook for polymodel to override. For regular models and expandos this is just an alias for _get_kind(). For PolyModel subclasses, it returns the class name (as set in the \'class\' attribute thereof), whereas _get_kind() returns the kind (the class name of the root class of a specific PolyModel hierarchy).'
@classmethod def _class_name(cls):
return cls._get_kind()
'Return an iterable of filters that are always to be applied. This is used by PolyModel to quietly insert a filter for the current class name.'
@classmethod def _default_filters(cls):
return ()
'Clear the kind map. Useful for testing.'
@classmethod def _reset_kind_map(cls):
keep = {} for (name, value) in cls._kind_map.iteritems(): if (name.startswith('__') and name.endswith('__')): keep[name] = value cls._kind_map.clear() cls._kind_map.update(keep)
'Get the model class for the kind. Args: kind: A string representing the name of the kind to lookup. default_model: The model class to use if the kind can\'t be found. Returns: The model class for the requested kind. Raises: KindError: The kind was not found and no default_model was provided.'
@classmethod def _lookup_model(cls, kind, default_model=None):
modelclass = cls._kind_map.get(kind, default_model) if (modelclass is None): raise KindError(("No model class found for kind '%s'. Did you forget to import it?" % kind)) return modelclass
'Return whether this entity has a complete key.'
def _has_complete_key(self):
return ((self._key is not None) and (self._key.id() is not None))
'Dummy hash function. Raises: Always TypeError to emphasize that entities are mutable.'
def __hash__(self):
raise TypeError('Model is not immutable')
'Compare two entities of the same class for equality.'
def __eq__(self, other):
if (other.__class__ is not self.__class__): return NotImplemented if (self._key != other._key): return False return self._equivalent(other)
'Compare two entities of the same class, excluding keys.'
def _equivalent(self, other):
if (other.__class__ is not self.__class__): raise NotImplementedError(('Cannot compare different model classes. %s is not %s' % (self.__class__.__name__, other.__class_.__name__))) if (set(self._projection) != set(other._projection)): return False if (len(self._proper...
'Internal helper to turn an entity into an EntityProto protobuf.'
def _to_pb(self, pb=None, allow_partial=False, set_key=True):
if (not allow_partial): self._check_initialized() if (pb is None): pb = entity_pb.EntityProto() if set_key: self._key_to_pb(pb) for (unused_name, prop) in sorted(self._properties.iteritems()): prop._serialize(self, pb, projection=self._projection) return pb
'Internal helper to copy the key into a protobuf.'
def _key_to_pb(self, pb):
key = self._key if (key is None): pairs = [(self._get_kind(), None)] ref = key_module._ReferenceFromPairs(pairs, reference=pb.mutable_key()) else: ref = key.reference() pb.mutable_key().CopyFrom(ref) group = pb.mutable_entity_group() if ((key is not None) and key.id()...
'Internal helper to create an entity from an EntityProto protobuf.'
@classmethod def _from_pb(cls, pb, set_key=True, ent=None, key=None):
if (not isinstance(pb, entity_pb.EntityProto)): raise TypeError(('pb must be a EntityProto; received %r' % pb)) if (ent is None): ent = cls() if ((key is None) and pb.key().path().element_size()): key = Key(reference=pb.key()) if ((key is not None) and (set_key ...
'Internal helper to get the Property for a protobuf-level property.'
def _get_property_for(self, p, indexed=True, depth=0):
name = p.name() parts = name.split('.') if (len(parts) <= depth): return None next = parts[depth] prop = self._properties.get(next) if (prop is None): prop = self._fake_property(p, next, indexed) return prop
'Internal helper to clone self._properties if necessary.'
def _clone_properties(self):
cls = self.__class__ if (self._properties is cls._properties): self._properties = dict(cls._properties)
'Internal helper to create a fake Property.'
def _fake_property(self, p, next, indexed=True):
self._clone_properties() if ((p.name() != next) and (not p.name().endswith(('.' + next)))): prop = StructuredProperty(Expando, next) prop._store_value(self, _BaseValue(Expando())) else: compressed = (p.meaning_uri() == _MEANING_URI_COMPRESSED) prop = GenericProperty(next, rep...
'Return a dict containing the entity\'s property values. Args: include: Optional set of property names to include, default all. exclude: Optional set of property names to skip, default none. A name contained in both include and exclude is excluded.'
@utils.positional(1) def _to_dict(self, include=None, exclude=None):
if ((include is not None) and (not isinstance(include, (list, tuple, set, frozenset)))): raise TypeError('include should be a list, tuple or set') if ((exclude is not None) and (not isinstance(exclude, (list, tuple, set, frozenset)))): raise TypeError('exclude should b...
'Fix up the properties by calling their _fix_up() method. Note: This is called by MetaModel, but may also be called manually after dynamically updating a model class.'
@classmethod def _fix_up_properties(cls):
kind = cls._get_kind() if (not isinstance(kind, basestring)): raise KindError(('Class %s defines a _get_kind() method that returns a non-string (%r)' % (cls.__name__, kind))) if (not isinstance(kind, str)): try: kind = kind.encode('ascii') ex...
'Update the kind map to include this class.'
@classmethod def _update_kind_map(cls):
cls._kind_map[cls._get_kind()] = cls
'Internal helper to check the given properties exist and meet specified requirements. Called from query.py. Args: property_names: List or tuple of property names -- each being a string, possibly containing dots (to address subproperties of structured properties). Raises: InvalidPropertyError if one of the properties is...
@classmethod def _check_properties(cls, property_names, require_indexed=True):
assert isinstance(property_names, (list, tuple)), repr(property_names) for name in property_names: assert isinstance(name, basestring), repr(name) if ('.' in name): (name, rest) = name.split('.', 1) else: rest = None prop = cls._properties.get(name) ...
'Internal helper to raise an exception for an unknown property name. This is called by _check_properties(). It is overridden by Expando, where this is a no-op. Raises: InvalidPropertyError.'
@classmethod def _unknown_property(cls, name):
raise InvalidPropertyError(('Unknown property %s' % name))
'Validation for _key attribute (designed to be overridden). Args: key: Proposed Key to use for entity. Returns: A valid key.'
def _validate_key(self, key):
return key
'Create a Query object for this class. Args: distinct: Optional bool, short hand for group_by = projection. *args: Used to apply an initial filter **kwds: are passed to the Query() constructor. Returns: A Query object.'
@classmethod def _query(cls, *args, **kwds):
if ('distinct' in kwds): if ('group_by' in kwds): raise TypeError('cannot use distinct= and group_by= at the same time') projection = kwds.get('projection') if (not projection): raise TypeError('cannot use distinct= without projecti...
'Run a GQL query.'
@classmethod def _gql(cls, query_string, *args, **kwds):
from .query import gql return gql(('SELECT * FROM %s %s' % (cls._class_name(), query_string)), *args, **kwds)
'Write this entity to the datastore. If the operation creates or completes a key, the entity\'s key attribute is set to the new, complete key. Returns: The key for the entity. This is always a complete key.'
def _put(self, **ctx_options):
return self._put_async(**ctx_options).get_result()
'Write this entity to the datastore. This is the asynchronous version of Model._put().'
def _put_async(self, **ctx_options):
if self._projection: raise datastore_errors.BadRequestError('Cannot put a partial entity') from . import tasklets ctx = tasklets.get_context() self._prepare_for_put() if (self._key is None): self._key = Key(self._get_kind(), None) self._pre_put_hook() fut = ctx.pu...
'Transactionally retrieves an existing entity or creates a new one. Positional Args: name: Key name to retrieve or create. Keyword Args: namespace: Optional namespace. app: Optional app ID. parent: Parent entity key, if any. context_options: ContextOptions object (not keyword args!) or None. **kwds: Keyword arguments t...
@classmethod def _get_or_insert(*args, **kwds):
(cls, args) = (args[0], args[1:]) return cls._get_or_insert_async(*args, **kwds).get_result()
'Transactionally retrieves an existing entity or creates a new one. This is the asynchronous version of Model._get_or_insert().'
@classmethod def _get_or_insert_async(*args, **kwds):
from . import tasklets (cls, name) = args get_arg = cls.__get_arg app = get_arg(kwds, 'app') namespace = get_arg(kwds, 'namespace') parent = get_arg(kwds, 'parent') context_options = get_arg(kwds, 'context_options') if (not isinstance(name, basestring)): raise TypeError(('name ...
'Allocates a range of key IDs for this model class. Args: size: Number of IDs to allocate. Either size or max can be specified, not both. max: Maximum ID to allocate. Either size or max can be specified, not both. parent: Parent key for which the IDs will be allocated. **ctx_options: Context options. Returns: A tuple w...
@classmethod def _allocate_ids(cls, size=None, max=None, parent=None, **ctx_options):
return cls._allocate_ids_async(size=size, max=max, parent=parent, **ctx_options).get_result()
'Allocates a range of key IDs for this model class. This is the asynchronous version of Model._allocate_ids().'
@classmethod def _allocate_ids_async(cls, size=None, max=None, parent=None, **ctx_options):
from . import tasklets ctx = tasklets.get_context() cls._pre_allocate_ids_hook(size, max, parent) key = Key(cls._get_kind(), None, parent=parent) fut = ctx.allocate_ids(key, size=size, max=max, **ctx_options) post_hook = cls._post_allocate_ids_hook if (not cls._is_default_hook(Model._default...
'Returns an instance of Model class by ID. This is really just a shorthand for Key(cls, id, ...).get(). Args: id: A string or integer key ID. parent: Optional parent key of the model to get. namespace: Optional namespace. app: Optional app ID. **ctx_options: Context options. Returns: A model instance or None if not fou...
@classmethod @utils.positional(3) def _get_by_id(cls, id, parent=None, **ctx_options):
return cls._get_by_id_async(id, parent=parent, **ctx_options).get_result()
'Returns an instance of Model class by ID (and app, namespace). This is the asynchronous version of Model._get_by_id().'
@classmethod @utils.positional(3) def _get_by_id_async(cls, id, parent=None, app=None, namespace=None, **ctx_options):
key = Key(cls._get_kind(), id, parent=parent, app=app, namespace=namespace) return key.get_async(**ctx_options)
'Checks whether a specific hook is in its default state. Args: cls: A ndb.model.Model class. default_hook: Callable specified by ndb internally (do not override). hook: The hook defined by a model class using _post_*_hook. Raises: TypeError if either the default hook or the tested hook are not callable.'
@staticmethod def _is_default_hook(default_hook, hook):
if (not hasattr(default_hook, '__call__')): raise TypeError('Default hooks for ndb.model.Model must be callable') if (not hasattr(hook, '__call__')): raise TypeError('Hooks must be callable') return (default_hook.im_func is hook.im_func)
'Constructor. If you really want to you can give this a different datastore name or make it unindexed. For example: class Foo(PolyModel): class_ = _ClassKeyProperty(indexed=False)'
def __init__(self, name=_CLASS_KEY_PROPERTY, indexed=True):
super(_ClassKeyProperty, self).__init__(name=name, indexed=indexed, repeated=True)
'The class_ property is read-only from the user\'s perspective.'
def _set_value(self, entity, value):
raise TypeError(('%s is a read-only property' % self._code_name))
'Compute and store a default value if necessary.'
def _get_value(self, entity):
value = super(_ClassKeyProperty, self)._get_value(entity) if (not value): value = entity._class_key() self._store_value(entity, value) return value
'Ensure the class_ property is initialized before it is serialized.'
def _prepare_for_put(self, entity):
self._get_value(entity)
'Override; called by Model._fix_up_properties(). Update the kind map as well as the class map, except for PolyModel itself (its class key is empty). Note that the kind map will contain entries for all classes in a PolyModel hierarchy; they all have the same kind, but different class names. PolyModel class names, like...
@classmethod def _update_kind_map(cls):
cls._kind_map[cls._class_name()] = cls class_key = cls._class_key() if class_key: cls._class_map[tuple(class_key)] = cls
'Override. Use the class map to give the entity the correct subclass.'
@classmethod def _from_pb(cls, pb, set_key=True, ent=None, key=None):
prop_name = cls.class_._name class_name = [] for plist in [pb.property_list(), pb.raw_property_list()]: for p in plist: if (p.name() == prop_name): class_name.append(p.value().stringvalue()) cls = cls._class_map.get(tuple(class_name), cls) return super(PolyModel, ...
'Return the class key. This is a list of class names, e.g. [\'Animal\', \'Feline\', \'Cat\'].'
@classmethod def _class_key(cls):
return [c._class_name() for c in cls._get_hierarchy()]
'Override. Make sure that the kind returned is the root class of the polymorphic hierarchy.'
@classmethod def _get_kind(cls):
bases = cls._get_hierarchy() if (not bases): return model.Model._get_kind.im_func(cls) else: return bases[0]._class_name()
'Return the class name. This overrides Model._class_name() which is an alias for _get_kind(). This is overridable in case you want to use a different class name. The main use case is probably to maintain backwards compatibility with datastore contents after renaming a class. NOTE: When overriding this for an intermedi...
@classmethod def _class_name(cls):
return cls.__name__
'Internal helper to return the list of polymorphic base classes. This returns a list of class objects, e.g. [Animal, Feline, Cat].'
@classmethod def _get_hierarchy(cls):
bases = [] for base in cls.mro(): if hasattr(base, '_get_hierarchy'): bases.append(base) del bases[(-1)] bases.reverse() return bases
'Constructor. Fields: current: a FIFO list of (callback, args, kwds). These callbacks run immediately when the eventloop runs. idlers: a FIFO list of (callback, args, kwds). Thes callbacks run only when no other RPCs need to be fired first. For example, AutoBatcher uses idler to fire a batch RPC even before the batch i...
def __init__(self):
self.current = collections.deque() self.idlers = collections.deque() self.inactive = 0 self.queue = [] self.rpcs = {}
'Remove all pending events without running any.'
def clear(self):
while (self.current or self.idlers or self.queue or self.rpcs): current = self.current idlers = self.idlers queue = self.queue rpcs = self.rpcs _logging_debug('Clearing stale EventLoop instance...') if current: _logging_debug(' current =...
'Insert event in queue, and keep it sorted assuming queue is sorted. If event is already in queue, insert it to the right of the rightmost event (to keep FIFO order). Optional args lo (default 0) and hi (default len(a)) bound the slice of a to be searched. Args: event: a (time in sec since unix epoch, callback, args, k...
def insort_event_right(self, event, lo=0, hi=None):
if (lo < 0): raise ValueError('lo must be non-negative') if (hi is None): hi = len(self.queue) while (lo < hi): mid = ((lo + hi) // 2) if (event[0] < self.queue[mid][0]): hi = mid else: lo = (mid + 1) self.queue.insert(lo, event)
'Schedule a function call at a specific time in the future.'
def queue_call(self, delay, callback, *args, **kwds):
if (delay is None): self.current.append((callback, args, kwds)) return if (delay < 1000000000.0): when = (delay + time.time()) else: when = delay self.insort_event_right((when, callback, args, kwds))
'Schedule an RPC with an optional callback. The caller must have previously sent the call to the service. The optional callback is called with the remaining arguments. NOTE: If the rpc is a MultiRpc, the callback will be called once for each sub-RPC. TODO: Is this a good idea?'
def queue_rpc(self, rpc, callback=None, *args, **kwds):
if (rpc is None): return if (rpc.state not in (_RUNNING, _FINISHING)): raise RuntimeError('rpc must be sent to service before queueing') if isinstance(rpc, datastore_rpc.MultiRpc): rpcs = rpc.rpcs if (len(rpcs) > 1): rpc.__done = False ...
'Add an idle callback. An idle callback can return True, False or None. These mean: - None: remove the callback (don\'t reschedule) - False: the callback did no work; reschedule later - True: the callback did some work; reschedule soon If the callback raises an exception, the traceback is logged and the callback is re...
def add_idle(self, callback, *args, **kwds):
self.idlers.append((callback, args, kwds))
'Run one of the idle callbacks. Returns: True if one was called, False if no idle callback was called.'
def run_idle(self):
if ((not self.idlers) or (self.inactive >= len(self.idlers))): return False idler = self.idlers.popleft() (callback, args, kwds) = idler _logging_debug('idler: %s', callback.__name__) res = callback(*args, **kwds) if (res is not None): if res: self.inactive = 0 ...
'Run one item (a callback or an RPC wait_any). Returns: A time to sleep if something happened (may be 0); None if all queues are empty.'
def run0(self):
if self.current: self.inactive = 0 (callback, args, kwds) = self.current.popleft() _logging_debug('nowevent: %s', callback.__name__) callback(*args, **kwds) return 0 if self.run_idle(): return 0 delay = None if self.queue: delay = (self.queue[0]...
'Run one item (a callback or an RPC wait_any) or sleep. Returns: True if something happened; False if all queues are empty.'
def run1(self):
delay = self.run0() if (delay is None): return False if (delay > 0): time.sleep(delay) return True
'Run until there\'s nothing left to do.'
def run(self):
self.inactive = 0 while True: if (not self.run1()): break
'Init. Args: todo_tasklet: the tasklet that actually fires RPC and waits on a MultiRPC. It should take a list of (future, arg) pairs and an "options" as arguments. "options" are rpc options. limit: max number of items to batch for each distinct value of "options".'
def __init__(self, todo_tasklet, limit):
self._todo_tasklet = todo_tasklet self._limit = limit self._queues = {} self._running = [] self._cache = {}
'Actually run the _todo_tasklet.'
def run_queue(self, options, todo):
utils.logging_debug('AutoBatcher(%s): %d items', self._todo_tasklet.__name__, len(todo)) batch_fut = self._todo_tasklet(todo, options) self._running.append(batch_fut) batch_fut.add_callback(self._finished_callback, batch_fut, todo)
'An idler eventloop can run. Eventloop calls this when it has finished processing all immediate callbacks. This method runs _todo_tasklet even before the batch is full.'
def _on_idle(self):
if (not self.action()): return None return True
'Adds an arg and gets back a future. Args: arg: one argument for _todo_tasklet. options: rpc options. Return: An instance of future, representing the result of running _todo_tasklet without batching.'
def add(self, arg, options=None):
fut = tasklets.Future(('%s.add(%s, %s)' % (self, arg, options))) todo = self._queues.get(options) if (todo is None): utils.logging_debug('AutoBatcher(%s): creating new queue for %r', self._todo_tasklet.__name__, options) if (not self._queues): eventloop.add_idle...
'Passes exception along. Args: batch_fut: the batch future returned by running todo_tasklet. todo: (fut, option) pair. fut is the future return by each add() call. If the batch fut was successful, it has already called fut.set_result() on other individual futs. This method only handles when the batch fut encountered an...
def _finished_callback(self, batch_fut, todo):
self._running.remove(batch_fut) err = batch_fut.get_exception() if (err is not None): tb = batch_fut.get_traceback() for (fut, _) in todo: if (not fut.done()): fut.set_exception(err, tb)
'Default cache policy. This defers to _use_cache on the Model class. Args: key: Key instance. Returns: A bool or None.'
@staticmethod def default_cache_policy(key):
flag = None if (key is not None): modelclass = model.Model._kind_map.get(key.kind()) if (modelclass is not None): policy = getattr(modelclass, '_use_cache', None) if (policy is not None): if isinstance(policy, bool): flag = policy ...
'Return the current context cache policy function. Returns: A function that accepts a Key instance as argument and returns a bool indicating if it should be cached. May be None.'
def get_cache_policy(self):
return self._cache_policy
'Set the context cache policy function. Args: func: A function that accepts a Key instance as argument and returns a bool indicating if it should be cached. May be None.'
def set_cache_policy(self, func):
if (func is None): func = self.default_cache_policy elif isinstance(func, bool): func = (lambda unused_key, flag=func: flag) self._cache_policy = func
'Return whether to use the context cache for this key. Args: key: Key instance. options: ContextOptions instance, or None. Returns: True if the key should be cached, False otherwise.'
def _use_cache(self, key, options=None):
flag = ContextOptions.use_cache(options) if (flag is None): flag = self._cache_policy(key) if (flag is None): flag = ContextOptions.use_cache(self._conn.config) if (flag is None): flag = True return flag
'Default memcache policy. This defers to _use_memcache on the Model class. Args: key: Key instance. Returns: A bool or None.'
@staticmethod def default_memcache_policy(key):
flag = None if (key is not None): modelclass = model.Model._kind_map.get(key.kind()) if (modelclass is not None): policy = getattr(modelclass, '_use_memcache', None) if (policy is not None): if isinstance(policy, bool): flag = policy ...
'Return the current memcache policy function. Returns: A function that accepts a Key instance as argument and returns a bool indicating if it should be cached. May be None.'
def get_memcache_policy(self):
return self._memcache_policy
'Set the memcache policy function. Args: func: A function that accepts a Key instance as argument and returns a bool indicating if it should be cached. May be None.'
def set_memcache_policy(self, func):
if (func is None): func = self.default_memcache_policy elif isinstance(func, bool): func = (lambda unused_key, flag=func: flag) self._memcache_policy = func
'Return whether to use memcache for this key. Args: key: Key instance. options: ContextOptions instance, or None. Returns: True if the key should be cached in memcache, False otherwise.'
def _use_memcache(self, key, options=None):
flag = ContextOptions.use_memcache(options) if (flag is None): flag = self._memcache_policy(key) if (flag is None): flag = ContextOptions.use_memcache(self._conn.config) if (flag is None): flag = True return flag
'Default datastore policy. This defers to _use_datastore on the Model class. Args: key: Key instance. Returns: A bool or None.'
@staticmethod def default_datastore_policy(key):
flag = None if (key is not None): modelclass = model.Model._kind_map.get(key.kind()) if (modelclass is not None): policy = getattr(modelclass, '_use_datastore', None) if (policy is not None): if isinstance(policy, bool): flag = policy ...
'Return the current context datastore policy function. Returns: A function that accepts a Key instance as argument and returns a bool indicating if it should use the datastore. May be None.'
def get_datastore_policy(self):
return self._datastore_policy
'Set the context datastore policy function. Args: func: A function that accepts a Key instance as argument and returns a bool indicating if it should use the datastore. May be None.'
def set_datastore_policy(self, func):
if (func is None): func = self.default_datastore_policy elif isinstance(func, bool): func = (lambda unused_key, flag=func: flag) self._datastore_policy = func
'Return whether to use the datastore for this key. Args: key: Key instance. options: ContextOptions instance, or None. Returns: True if the datastore should be used, False otherwise.'
def _use_datastore(self, key, options=None):
flag = ContextOptions.use_datastore(options) if (flag is None): flag = self._datastore_policy(key) if (flag is None): flag = ContextOptions.use_datastore(self._conn.config) if (flag is None): flag = True return flag
'Default memcache timeout policy. This defers to _memcache_timeout on the Model class. Args: key: Key instance. Returns: Memcache timeout to use (integer), or None.'
@staticmethod def default_memcache_timeout_policy(key):
timeout = None if ((key is not None) and isinstance(key, model.Key)): modelclass = model.Model._kind_map.get(key.kind()) if (modelclass is not None): policy = getattr(modelclass, '_memcache_timeout', None) if (policy is not None): if isinstance(policy, (in...
'Set the policy function for memcache timeout (expiration). Args: func: A function that accepts a key instance as argument and returns an integer indicating the desired memcache timeout. May be None. If the function returns 0 it implies the default timeout.'
def set_memcache_timeout_policy(self, func):
if (func is None): func = self.default_memcache_timeout_policy elif isinstance(func, (int, long)): func = (lambda unused_key, flag=func: flag) self._memcache_timeout_policy = func
'Return the current policy function for memcache timeout (expiration).'
def get_memcache_timeout_policy(self):
return self._memcache_timeout_policy
'Return the memcache timeout (expiration) for this key.'
def _get_memcache_timeout(self, key, options=None):
timeout = ContextOptions.memcache_timeout(options) if (timeout is None): timeout = self._memcache_timeout_policy(key) if (timeout is None): timeout = ContextOptions.memcache_timeout(self._conn.config) if (timeout is None): timeout = 0 return timeout
'Return the memcache RPC deadline. Not to be confused with the memcache timeout, or expiration. This is only used by datastore operations when using memcache as a cache; it is ignored by the direct memcache calls. There is no way to vary this per key or per entity; you must either set it on a specific call (e.g. key.ge...
def _get_memcache_deadline(self, options=None):
return ContextOptions.memcache_deadline(options, self._conn.config)