desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Convert a base type (integer) value to an Enum value.'
def _from_base_type(self, val):
return self._enum_type(val)
'Constructor. Args: message_tyoe: A subclass of protorpc.messages.Message. name: Optional datastore name (defaults to the property name). indexed_fields: Optional list of dotted and undotted field names. protocol: Optional protocol name default \'protobuf\'. Additional keywords arguments specify the same options as sup...
@utils.positional((1 + model.StructuredProperty._positional)) def __init__(self, message_type, name=None, indexed_fields=None, protocol=None, **kwds):
if (not (isinstance(message_type, type) and issubclass(message_type, messages.Message))): raise TypeError('MessageProperty argument must be a Message subclass') self._message_type = message_type if (indexed_fields is not None): self._indexed_fields = tuple(indexed_fields) ...
'Validate an Enum value. Raises: TypeError if the value is not an instance of self._message_type.'
def _validate(self, msg):
if (not isinstance(msg, self._message_type)): raise TypeError('Expected a %s instance for %s property', self._message_type.__name__, (self._code_name or self._name))
'Convert a Message value to a Model instance (entity).'
def _to_base_type(self, msg):
ent = _message_to_entity(msg, self._modelclass) ent.blob_ = self._protocol_impl.encode_message(msg) return ent
'Convert a Model instance (entity) to a Message value.'
def _from_base_type(self, ent):
if ent._projection: return _projected_entity_to_message(ent, self._message_type) blob = ent.blob_ if (blob is not None): protocol = self._protocol_impl else: protocol = None for name in _protocols_registry.names: key = ('__%s__' % name) if (key in ...
'Constructor. See the class docstring for arguments.'
def __new__(cls, *_args, **kwargs):
if _args: if ((len(_args) == 1) and isinstance(_args[0], dict)): if kwargs: raise TypeError('Key() takes no keyword arguments when a dict is the the first and only non-keyword argument (for unpickling).') kwargs = _ar...
'String representation, used by str() and repr(). We produce a short string that conveys all relevant information, suppressing app and namespace when they are equal to the default.'
def __repr__(self):
args = [] for item in self.flat(): if (not item): args.append('None') elif isinstance(item, basestring): if (not isinstance(item, str)): raise TypeError(('Key item is not an 8-bit string %r' % item)) args.append(repr(item))...
'Hash value, for use in dict lookups.'
def __hash__(self):
return hash(tuple(self.pairs()))
'Equality comparison operation.'
def __eq__(self, other):
if (not isinstance(other, Key)): return NotImplemented return ((tuple(self.pairs()) == tuple(other.pairs())) and (self.app() == other.app()) and (self.namespace() == other.namespace()))
'The opposite of __eq__.'
def __ne__(self, other):
if (not isinstance(other, Key)): return NotImplemented return (not self.__eq__(other))
'Helper to return an orderable tuple.'
def __tuple(self):
return (self.app(), self.namespace(), self.pairs())
'Less than ordering.'
def __lt__(self, other):
if (not isinstance(other, Key)): return NotImplemented return (self.__tuple() < other.__tuple())
'Less than or equal ordering.'
def __le__(self, other):
if (not isinstance(other, Key)): return NotImplemented return (self.__tuple() <= other.__tuple())
'Greater than ordering.'
def __gt__(self, other):
if (not isinstance(other, Key)): return NotImplemented return (self.__tuple() > other.__tuple())
'Greater than or equal ordering.'
def __ge__(self, other):
if (not isinstance(other, Key)): return NotImplemented return (self.__tuple() >= other.__tuple())
'Private API used for pickling.'
def __getstate__(self):
return ({'pairs': list(self.pairs()), 'app': self.app(), 'namespace': self.namespace()},)
'Private API used for pickling.'
def __setstate__(self, state):
if (len(state) != 1): raise TypeError(('Invalid state length, expected 1; received %i' % len(state))) kwargs = state[0] if (not isinstance(kwargs, dict)): raise TypeError(('Key accepts a dict of keyword arguments as state; received %r' % kwargs...
'Private API used for pickling.'
def __getnewargs__(self):
return ({'pairs': tuple(self.pairs()), 'app': self.app(), 'namespace': self.namespace()},)
'Return a Key constructed from all but the last (kind, id) pairs. If there is only one (kind, id) pair, return None.'
def parent(self):
pairs = self.pairs() if (len(pairs) <= 1): return None return Key(pairs=pairs[:(-1)], app=self.app(), namespace=self.namespace())
'Return the root key. This is either self or the highest parent.'
def root(self):
pairs = self.pairs() if (len(pairs) <= 1): return self return Key(pairs=pairs[:1], app=self.app(), namespace=self.namespace())
'Return the namespace.'
def namespace(self):
if (self.__namespace is None): self.__namespace = self.__reference.name_space() return self.__namespace
'Return the application id.'
def app(self):
if (self.__app is None): self.__app = self.__reference.app() return self.__app
'Return the string or integer id in the last (kind, id) pair, if any. Returns: A string or integer id, or None if the key is incomplete.'
def id(self):
if self.__pairs: return self.__pairs[(-1)][1] elem = self.__reference.path().element((-1)) return (elem.name() or elem.id() or None)
'Return the string id in the last (kind, id) pair, if any. Returns: A string id, or None if the key has an integer id or is incomplete.'
def string_id(self):
if (self.__reference is None): id = self.id() if (not isinstance(id, basestring)): id = None return id elem = self.__reference.path().element((-1)) return (elem.name() or None)
'Return the integer id in the last (kind, id) pair, if any. Returns: An integer id, or None if the key has a string id or is incomplete.'
def integer_id(self):
if (self.__reference is None): id = self.id() if (not isinstance(id, (int, long))): id = None return id elem = self.__reference.path().element((-1)) return (elem.id() or None)
'Return a tuple of (kind, id) pairs.'
def pairs(self):
pairs = self.__pairs if (pairs is None): pairs = [] for elem in self.__reference.path().element_list(): kind = elem.type() if elem.has_id(): id_or_name = elem.id() else: id_or_name = elem.name() if (not id_or_name): ...
'Return a tuple of alternating kind and id values.'
def flat(self):
flat = [] for (kind, id) in self.pairs(): flat.append(kind) flat.append(id) return tuple(flat)
'Return the kind of the entity referenced. This is the kind from the last (kind, id) pair.'
def kind(self):
if self.__pairs: return self.__pairs[(-1)][0] return self.__reference.path().element((-1)).type()
'Return the Reference object for this Key. This is a entity_pb.Reference instance -- a protocol buffer class used by the lower-level API to the datastore. NOTE: The caller should not mutate the return value.'
def reference(self):
if (self.__reference is None): self.__reference = _ConstructReference(self.__class__, pairs=self.__pairs, app=self.__app, namespace=self.__namespace) return self.__reference
'Return a serialized Reference object for this Key.'
def serialized(self):
return self.reference().Encode()
'Return a url-safe string encoding this Key\'s Reference. This string is compatible with other APIs and languages and with the strings used to represent Keys in GQL and in the App Engine Admin Console.'
def urlsafe(self):
urlsafe = base64.b64encode(self.reference().Encode()) return urlsafe.rstrip('=').replace('+', '-').replace('/', '_')
'Synchronously get the entity for this Key. Return None if there is no such entity.'
def get(self, **ctx_options):
return self.get_async(**ctx_options).get_result()
'Return a Future whose result is the entity for this Key. If no such entity exists, a Future is still returned, and the Future\'s eventual return result be None.'
def get_async(self, **ctx_options):
from . import model, tasklets ctx = tasklets.get_context() cls = model.Model._kind_map.get(self.kind()) if cls: cls._pre_get_hook(self) fut = ctx.get(self, **ctx_options) if cls: post_hook = cls._post_get_hook if (not cls._is_default_hook(model.Model._default_post_get_hoo...
'Synchronously delete the entity for this Key. This is a no-op if no such entity exists.'
def delete(self, **ctx_options):
return self.delete_async(**ctx_options).get_result()
'Schedule deletion of the entity for this Key. This returns a Future, whose result becomes available once the deletion is complete. If no such entity exists, a Future is still returned. In all cases the Future\'s result is None (i.e. there is no way to tell whether the entity existed or not).'
def delete_async(self, **ctx_options):
from . import tasklets, model ctx = tasklets.get_context() cls = model.Model._kind_map.get(self.kind()) if cls: cls._pre_delete_hook(self) fut = ctx.delete(self, **ctx_options) if cls: post_hook = cls._post_delete_hook if (not cls._is_default_hook(model.Model._default_pos...
'Kind name override.'
@classmethod def _get_kind(cls):
return cls.KIND_NAME
'Return the namespace name specified by this entity\'s key.'
@property def namespace_name(self):
return self.key_to_namespace(self.key)
'Return the Key for a namespace. Args: namespace: A string giving the namespace whose key is requested. Returns: The Key for the namespace.'
@classmethod def key_for_namespace(cls, namespace):
if namespace: return model.Key(cls.KIND_NAME, namespace) else: return model.Key(cls.KIND_NAME, cls.EMPTY_NAMESPACE_ID)
'Return the namespace specified by a given __namespace__ key. Args: key: key whose name is requested. Returns: The namespace specified by key.'
@classmethod def key_to_namespace(cls, key):
return (key.string_id() or '')
'Return the kind name specified by this entity\'s key.'
@property def kind_name(self):
return self.key_to_kind(self.key)
'Return the __kind__ key for kind. Args: kind: kind whose key is requested. Returns: The key for kind.'
@classmethod def key_for_kind(cls, kind):
return model.Key(cls.KIND_NAME, kind)
'Return the kind specified by a given __kind__ key. Args: key: key whose name is requested. Returns: The kind specified by key.'
@classmethod def key_to_kind(cls, key):
return key.id()
'Return the property name specified by this entity\'s key.'
@property def property_name(self):
return self.key_to_property(self.key)
'Return the kind name specified by this entity\'s key.'
@property def kind_name(self):
return self.key_to_kind(self.key)
'Return the __property__ key for kind. Args: kind: kind whose key is requested. Returns: The parent key for __property__ keys of kind.'
@classmethod def key_for_kind(cls, kind):
return model.Key(Kind.KIND_NAME, kind)
'Return the __property__ key for property of kind. Args: kind: kind whose key is requested. property: property whose key is requested. Returns: The key for property of kind.'
@classmethod def key_for_property(cls, kind, property):
return model.Key(Kind.KIND_NAME, kind, Property.KIND_NAME, property)
'Return the kind specified by a given __property__ key. Args: key: key whose kind name is requested. Returns: The kind specified by key.'
@classmethod def key_to_kind(cls, key):
if (key.kind() == Kind.KIND_NAME): return key.id() else: return key.parent().id()
'Return the property specified by a given __property__ key. Args: key: key whose property name is requested. Returns: property specified by key, or None if the key specified only a kind.'
@classmethod def key_to_property(cls, key):
if (key.kind() == Kind.KIND_NAME): return None else: return key.id()
'Return the key for the entity group containing key. Args: key: a key for an entity group whose __entity_group__ key you want. Returns: The __entity_group__ key for the entity group containing key.'
@classmethod def key_for_entity_group(cls, key):
return model.Key(cls.KIND_NAME, cls.ID, parent=key.root())
'Implement self != other as not(self == other).'
def __ne__(self, other):
eq = self.__eq__(other) if (eq is NotImplemented): return NotImplemented return (not eq)
'Updates all descendants to a specified value.'
def _set(self, value):
if self.__is_parent_node(): for child in self.__sub_counters.itervalues(): child._set(value) else: self.__counter = value
'Constructor.'
@utils.positional(1) def __new__(cls, name, direction):
obj = object.__new__(cls) obj.__name = name obj.__direction = direction return obj
'The property name being indexed, a string.'
@property def name(self):
return self.__name
'The direction in the index for this property, \'asc\' or \'desc\'.'
@property def direction(self):
return self.__direction
'Return a string representation.'
def __repr__(self):
return ('%s(name=%r, direction=%r)' % (self.__class__.__name__, self.name, self.direction))
'Compare two index properties for equality.'
def __eq__(self, other):
if (not isinstance(other, IndexProperty)): return NotImplemented return ((self.name == other.name) and (self.direction == other.direction))
'Constructor.'
@utils.positional(1) def __new__(cls, kind, properties, ancestor):
obj = object.__new__(cls) obj.__kind = kind obj.__properties = properties obj.__ancestor = ancestor return obj
'The kind being indexed, a string.'
@property def kind(self):
return self.__kind
'A list of PropertyIndex objects giving the properties being indexed.'
@property def properties(self):
return self.__properties
'Whether this is an ancestor index, a bool.'
@property def ancestor(self):
return self.__ancestor
'Return a string representation.'
def __repr__(self):
parts = [] parts.append(('kind=%r' % self.kind)) parts.append(('properties=%r' % self.properties)) parts.append(('ancestor=%s' % self.ancestor)) return ('%s(%s)' % (self.__class__.__name__, ', '.join(parts)))
'Compare two indexes.'
def __eq__(self, other):
if (not isinstance(other, Index)): return NotImplemented return ((self.kind == other.kind) and (self.properties == other.properties) and (self.ancestor == other.ancestor))
'Constructor.'
@utils.positional(1) def __new__(cls, definition, state, id):
obj = object.__new__(cls) obj.__definition = definition obj.__state = state obj.__id = id return obj
'An Index object describing the index.'
@property def definition(self):
return self.__definition
'The index state, a string. Possible values are \'error\', \'deleting\', \'serving\' or \'building\'.'
@property def state(self):
return self.__state
'The index ID, an integer.'
@property def id(self):
return self.__id
'Return a string representation.'
def __repr__(self):
parts = [] parts.append(('definition=%r' % self.definition)) parts.append(('state=%r' % self.state)) parts.append(('id=%d' % self.id)) return ('%s(%s)' % (self.__class__.__name__, ', '.join(parts)))
'Compare two index states.'
def __eq__(self, other):
if (not isinstance(other, IndexState)): return NotImplemented return ((self.definition == other.definition) and (self.state == other.state) and (self.id == other.id))
'Constructor. Args: default_model: If an implementation for the kind cannot be found, use this model class. If none is specified, an exception will be thrown (default).'
def __init__(self, default_model=None):
self.default_model = default_model self.want_pbs = 0
'Constructor. Argument is the base value to be wrapped.'
def __init__(self, b_val):
assert (b_val is not None) assert (not isinstance(b_val, list)), repr(b_val) self.b_val = b_val
'Constructor. For arguments see the module docstring.'
@utils.positional((1 + _positional)) def __init__(self, name=None, indexed=None, repeated=None, required=None, default=None, choices=None, validator=None, verbose_name=None):
if (name is not None): if isinstance(name, unicode): name = name.encode('utf-8') if (not isinstance(name, str)): raise TypeError(('Name %r is not a string' % (name,))) if ('.' in name): raise ValueError(('Name %r cannot contain p...
'Return a compact unambiguous string representation of a property.'
def __repr__(self):
args = [] cls = self.__class__ for (i, attr) in enumerate(self._attributes): val = getattr(self, attr) if (val is not getattr(cls, attr)): if isinstance(val, type): s = val.__name__ else: s = repr(val) if (i >= cls._position...
'Internal hook used by property filters. Sometimes the low-level query interface needs a specific data type in order for the right filter to be constructed. See _comparison().'
def _datastore_type(self, value):
return value
'Internal helper for comparison operators. Args: op: The operator (\'=\', \'<\' etc.). Returns: A FilterNode instance representing the requested comparison.'
def _comparison(self, op, value):
if (not self._indexed): raise datastore_errors.BadFilterError(('Cannot query for unindexed property %s' % self._name)) from .query import FilterNode if (value is not None): value = self._do_validate(value) value = self._call_to_base_type(value) value = self._da...
'Return a FilterNode instance representing the \'=\' comparison.'
def __eq__(self, value):
return self._comparison('=', value)
'Return a FilterNode instance representing the \'!=\' comparison.'
def __ne__(self, value):
return self._comparison('!=', value)
'Return a FilterNode instance representing the \'<\' comparison.'
def __lt__(self, value):
return self._comparison('<', value)
'Return a FilterNode instance representing the \'<=\' comparison.'
def __le__(self, value):
return self._comparison('<=', value)
'Return a FilterNode instance representing the \'>\' comparison.'
def __gt__(self, value):
return self._comparison('>', value)
'Return a FilterNode instance representing the \'>=\' comparison.'
def __ge__(self, value):
return self._comparison('>=', value)
'Comparison operator for the \'in\' comparison operator. The Python \'in\' operator cannot be overloaded in the way we want to, so we define a method. For example: Employee.query(Employee.rank.IN([4, 5, 6])) Note that the method is called ._IN() but may normally be invoked as .IN(); ._IN() is provided for the case you...
def _IN(self, value):
if (not self._indexed): raise datastore_errors.BadFilterError(('Cannot query for unindexed property %s' % self._name)) from .query import FilterNode if (not isinstance(value, (list, tuple, set, frozenset))): raise datastore_errors.BadArgumentError(('Expected list, tuple ...
'Return a descending sort order on this Property. For example: Employee.query().order(-Employee.rank)'
def __neg__(self):
return datastore_query.PropertyOrder(self._name, datastore_query.PropertyOrder.DESCENDING)
'Return an ascending sort order on this Property. Note that this is redundant but provided for consistency with __neg__. For example, the following two are equivalent: Employee.query().order(+Employee.rank) Employee.query().order(Employee.rank)'
def __pos__(self):
return datastore_query.PropertyOrder(self._name)
'Call all validations on the value. This calls the most derived _validate() method(s), then the custom validator function, and then checks the choices. It returns the value, possibly modified in an idempotent way, or raises an exception. Note that this does not call all composable _validate() methods. It only calls _v...
def _do_validate(self, value):
if isinstance(value, _BaseValue): return value value = self._call_shallow_validation(value) if (self._validator is not None): newvalue = self._validator(self, value) if (newvalue is not None): value = newvalue if (self._choices is not None): if (value not in s...
'Internal helper called to tell the property its name. This is called by _fix_up_properties() which is called by MetaModel when finishing the construction of a Model subclass. The name passed in is the name of the class attribute to which the Property is assigned (a.k.a. the code name). Note that this means that each ...
def _fix_up(self, cls, code_name):
self._code_name = code_name if (self._name is None): self._name = code_name
'Internal helper to store a value in an entity for a Property. This assumes validation has already taken place. For a repeated Property the value should be a list.'
def _store_value(self, entity, value):
entity._values[self._name] = value
'Internal helper to set a value in an entity for a Property. This performs validation first. For a repeated Property the value should be a list.'
def _set_value(self, entity, value):
if entity._projection: raise ReadonlyPropertyError('You cannot set property values of a projection entity') if self._repeated: if (not isinstance(value, (list, tuple, set, frozenset))): raise datastore_errors.BadValueError(('Expected list or tuple, ...
'Internal helper to ask if the entity has a value for this Property.'
def _has_value(self, entity, unused_rest=None):
return (self._name in entity._values)
'Internal helper to retrieve the value for this Property from an entity. This returns None if no value is set, or the default argument if given. For a repeated Property this returns a list if a value is set, otherwise None. No additional transformations are applied.'
def _retrieve_value(self, entity, default=None):
return entity._values.get(self._name, default)
'Return the user value for this property of the given entity. This implies removing the _BaseValue() wrapper if present, and if it is, calling all _from_base_type() methods, in the reverse method resolution order of the property\'s class. It also handles default values and repeated properties.'
def _get_user_value(self, entity):
return self._apply_to_values(entity, self._opt_call_from_base_type)
'Return the base value for this property of the given entity. This implies calling all _to_base_type() methods, in the method resolution order of the property\'s class, and adding a _BaseValue() wrapper, if one is not already present. (If one is present, no work is done.) It also handles default values and repeated p...
def _get_base_value(self, entity):
return self._apply_to_values(entity, self._opt_call_to_base_type)
'Like _get_base_value(), but always returns a list. Returns: A new list of unwrapped base values. For an unrepeated property, if the value is missing or None, returns [None]; for a repeated property, if the original value is missing or None or empty, returns [].'
def _get_base_value_unwrapped_as_list(self, entity):
wrapped = self._get_base_value(entity) if self._repeated: if (wrapped is None): return [] assert isinstance(wrapped, list) return [w.b_val for w in wrapped] else: if (wrapped is None): return [None] assert isinstance(wrapped, _BaseValue) ...
'Call _from_base_type() if necessary. If the value is a _BaseValue instance, unwrap it and call all _from_base_type() methods. Otherwise, return the value unchanged.'
def _opt_call_from_base_type(self, value):
if isinstance(value, _BaseValue): value = self._call_from_base_type(value.b_val) return value
'Turn a value (base or not) into its repr(). This exists so that property classes can override it separately.'
def _value_to_repr(self, value):
val = self._opt_call_from_base_type(value) return repr(val)
'Call _to_base_type() if necessary. If the value is a _BaseValue instance, return it unchanged. Otherwise, call all _validate() and _to_base_type() methods and wrap it in a _BaseValue instance.'
def _opt_call_to_base_type(self, value):
if (not isinstance(value, _BaseValue)): value = _BaseValue(self._call_to_base_type(value)) return value
'Call all _from_base_type() methods on the value. This calls the methods in the reverse method resolution order of the property\'s class.'
def _call_from_base_type(self, value):
methods = self._find_methods('_from_base_type', reverse=True) call = self._apply_list(methods) return call(value)
'Call all _validate() and _to_base_type() methods on the value. This calls the methods in the method resolution order of the property\'s class.'
def _call_to_base_type(self, value):
methods = self._find_methods('_validate', '_to_base_type') call = self._apply_list(methods) return call(value)
'Call the initial set of _validate() methods. This is similar to _call_to_base_type() except it only calls those _validate() methods that can be called without needing to call _to_base_type(). An example: suppose the class hierarchy is A -> B -> C -> Property, and suppose A defines _validate() only, but B and C define ...
def _call_shallow_validation(self, value):
methods = [] for method in self._find_methods('_validate', '_to_base_type'): if (method.__name__ != '_validate'): break methods.append(method) call = self._apply_list(methods) return call(value)
'Compute a list of composable methods. Because this is a common operation and the class hierarchy is static, the outcome is cached (assuming that for a particular list of names the reversed flag is either always on, or always off). Args: *names: One or more method names. reverse: Optional flag, default False; if True, ...
@classmethod def _find_methods(cls, *names, **kwds):
reverse = kwds.pop('reverse', False) assert (not kwds), repr(kwds) cache = cls.__dict__.get('_find_methods_cache') if cache: hit = cache.get(names) if (hit is not None): return hit else: cls._find_methods_cache = cache = {} methods = [] for c in cls.__mro_...
'Return a single callable that applies a list of methods to a value. If a method returns None, the last value is kept; if it returns some other value, that replaces the last value. Exceptions are not caught.'
def _apply_list(self, methods):
def call(value): for method in methods: newvalue = method(self, value) if (newvalue is not None): value = newvalue return value return call