desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Deletes this entity from the datastore. Args: config: datastore_rpc.Configuration to use for this request. Raises: TransactionFailedError if the data could not be committed.'
def delete(self, **kwargs):
datastore.Delete(self.key(), **kwargs) self._key = self.key() self._key_name = None self._parent_key = None self._entity = None
'Determine if entity is persisted in the datastore. New instances of Model do not start out saved in the data. Objects which are saved to or loaded from the Datastore will have a True saved state. Returns: True if object has been persisted to the datastore, otherwise False.'
def is_saved(self):
return (self._entity is not None)
'Determine if this model instance has a complete key. When not using a fully self-assigned Key, ids are not assigned until the data is saved to the Datastore, but instances with a key name always have a full key. Returns: True if the object has been persisted to the datastore or has a key or has a key_name, otherwise F...
def has_key(self):
return (self.is_saved() or self._key or self._key_name)
'Returns a list of all dynamic properties defined for instance.'
def dynamic_properties(self):
return []
'Alias for dyanmic_properties.'
def instance_properties(self):
return self.dynamic_properties()
'Get the parent of the model instance. Returns: Parent of contained entity or parent provided in constructor, None if instance has no parent.'
def parent(self):
if (self._parent is None): parent_key = self.parent_key() if (parent_key is not None): self._parent = get(parent_key) return self._parent
'Get the parent\'s key. This method is useful for avoiding a potential fetch from the datastore but still get information about the instances parent. Returns: Parent key of entity, None if there is no parent.'
def parent_key(self):
if (self._parent_key is not None): return self._parent_key elif (self._parent is not None): return self._parent.key() elif (self._entity is not None): return self._entity.parent() elif (self._key is not None): return self._key.parent() else: return None
'Generate an XML representation of this model instance. atom and gd:namespace properties are converted to XML according to their respective schemas. For more information, see: http://www.atomenabled.org/developers/syndication/ http://code.google.com/apis/gdata/common-elements.html'
def to_xml(self, _entity_class=datastore.Entity):
entity = self._populate_entity(_entity_class) return entity.ToXml()
'Fetch instance from the datastore of a specific Model type using key. We support Key objects and string keys (we convert them to Key objects automatically). Useful for ensuring that specific instance types are retrieved from the datastore. It also helps that the source code clearly indicates what kind of object is be...
@classmethod def get(cls, keys, **kwargs):
results = get(keys, **kwargs) if (results is None): return None if isinstance(results, Model): instances = [results] else: instances = results for instance in instances: if (not ((instance is None) or isinstance(instance, cls))): raise KindError(('Kind ...
'Get instance of Model class by its key\'s name. Args: key_names: A single key-name or a list of key-names. parent: Parent of instances to get. Can be a model or key. config: datastore_rpc.Configuration to use for this request.'
@classmethod def get_by_key_name(cls, key_names, parent=None, **kwargs):
try: parent = _coerce_to_key(parent) except BadKeyError as e: raise BadArgumentError(str(e)) (key_names, multiple) = datastore.NormalizeAndTypeCheck(key_names, basestring) keys = [datastore.Key.from_path(cls.kind(), name, parent=parent) for name in key_names] if multiple: ret...
'Get instance of Model class by id. Args: key_names: A single id or a list of ids. parent: Parent of instances to get. Can be a model or key. config: datastore_rpc.Configuration to use for this request.'
@classmethod def get_by_id(cls, ids, parent=None, **kwargs):
if isinstance(parent, Model): parent = parent.key() (ids, multiple) = datastore.NormalizeAndTypeCheck(ids, (int, long)) keys = [datastore.Key.from_path(cls.kind(), id, parent=parent) for id in ids] if multiple: return get(keys, **kwargs) else: return get(keys[0], **kwargs)
'Transactionally retrieve or create an instance of Model class. This acts much like the Python dictionary setdefault() method, where we first try to retrieve a Model instance with the given key name and parent. If it\'s not present, then we create a new instance (using the *kwds supplied) and insert that with the suppl...
@classmethod def get_or_insert(cls, key_name, **kwds):
def txn(): entity = cls.get_by_key_name(key_name, parent=kwds.get('parent')) if (entity is None): entity = cls(key_name=key_name, **kwds) entity.put() return entity return run_in_transaction(txn)
'Returns a query over all instances of this model from the datastore. Returns: Query that will retrieve all instances from entity collection.'
@classmethod def all(cls, **kwds):
return Query(cls, **kwds)
'Returns a query using GQL query string. See appengine/ext/gql for more information about GQL. Args: query_string: properly formatted GQL query string with the \'SELECT * FROM <entity>\' part omitted *args: rest of the positional arguments used to bind numeric references in the query. **kwds: dictionary-based arguments...
@classmethod def gql(cls, query_string, *args, **kwds):
return GqlQuery(('SELECT * FROM %s %s' % (cls.kind(), query_string)), *args, **kwds)
'Load dynamic properties from entity. Loads attributes which are not defined as part of the entity in to the model instance. Args: entity: Entity which contain values to search dyanmic properties for.'
@classmethod def _load_entity_values(cls, entity):
entity_values = {} for prop in cls.properties().values(): if (prop.name in entity): try: value = entity[prop.name] except KeyError: entity_values[prop.name] = [] else: if entity.is_projection(): value...
'Converts the entity representation of this model to an instance. Converts datastore.Entity instance to an instance of cls. Args: entity: Entity loaded directly from datastore. Raises: KindError when cls is incorrect model for entity.'
@classmethod def from_entity(cls, entity):
if (cls.kind() != entity.kind()): raise KindError(("Class %s cannot handle kind '%s'" % (repr(cls), entity.kind()))) entity_values = cls._load_entity_values(entity) if entity.key().has_id_or_name(): entity_values['key'] = entity.key() return cls(None, _from_entity=entity, ...
'Returns the datastore kind we use for this model. We just use the name of the model for now, ignoring potential collisions.'
@classmethod def kind(cls):
return cls.__name__
'Soon to be removed alias for kind.'
@classmethod def entity_type(cls):
return cls.kind()
'Returns a dictionary of all the properties defined for this model.'
@classmethod def properties(cls):
return dict(cls._properties)
'Soon to be removed alias for properties.'
@classmethod def fields(cls):
return cls.properties()
'Creates a new instance of this expando model. Args: parent: Parent instance for this instance or None, indicating a top- level instance. key_name: Name for new model instance. _app: Intentionally undocumented. args: Keyword arguments mapping to properties of model.'
def __init__(self, parent=None, key_name=None, _app=None, **kwds):
super(Expando, self).__init__(parent, key_name, _app, **kwds) self._dynamic_properties = {} for (prop, value) in kwds.iteritems(): if ((prop not in self._all_properties) and (prop != 'key')): if (not hasattr(getattr(type(self), prop, None), '__set__')): setattr(self, prop...
'Dynamically set field values that are not defined. Tries to set the value on the object normally, but failing that sets the value on the contained entity. Args: key: Name of attribute. value: Value to set for attribute. Must be compatible with datastore. Raises: ValueError on attempt to assign empty list.'
def __setattr__(self, key, value):
check_reserved_word(key) if ((key[:1] != '_') and (not hasattr(getattr(type(self), key, None), '__set__'))): if (value == []): raise ValueError(('Cannot store empty list to dynamic property %s' % key)) if (type(value) not in _ALLOWED_EXPANDO_PROPERTY_TYPES): ...
'Get attribute from expando. Must be overridden to allow dynamic properties to obscure class attributes. Since all attributes are stored in self._dynamic_properties, the normal __getattribute__ does not attempt to access it until __setattr__ is called. By then, the static attribute being overwritten has already been lo...
def __getattribute__(self, key):
if (not key.startswith('_')): dynamic_properties = self._dynamic_properties if ((dynamic_properties is not None) and (key in dynamic_properties)): return self.__getattr__(key) return super(Expando, self).__getattribute__(key)
'If no explicit attribute defined, retrieve value from entity. Tries to get the value on the object normally, but failing that retrieves value from contained entity. Args: key: Name of attribute. Raises: AttributeError when there is no attribute for key on object or contained entity.'
def __getattr__(self, key):
_dynamic_properties = self._dynamic_properties if ((_dynamic_properties is not None) and (key in _dynamic_properties)): return _dynamic_properties[key] else: return getattr(super(Expando, self), key)
'Remove attribute from expando. Expando is not like normal entities in that undefined fields can be removed. Args: key: Dynamic property to be deleted.'
def __delattr__(self, key):
if (self._dynamic_properties and (key in self._dynamic_properties)): del self._dynamic_properties[key] else: object.__delattr__(self, key)
'Determine which properties are particular to instance of entity. Returns: Set of names which correspond only to the dynamic properties.'
def dynamic_properties(self):
if (self._dynamic_properties is None): return [] return self._dynamic_properties.keys()
'Store to entity, deleting dynamic properties that no longer exist. When the expando is saved, it is possible that a given property no longer exists. In this case, the property will be removed from the saved instance. Args: entity: Entity which will receive dynamic properties.'
def _to_entity(self, entity):
super(Expando, self)._to_entity(entity) if (self._dynamic_properties is None): self._dynamic_properties = {} for (key, value) in self._dynamic_properties.iteritems(): entity[key] = value all_properties = set(self._dynamic_properties.iterkeys()) all_properties.update(self._all_propert...
'Load dynamic properties from entity. Expando needs to do a second pass to add the entity values which were ignored by Model because they didn\'t have an corresponding predefined property on the model. Args: entity: Entity which contain values to search dyanmic properties for.'
@classmethod def _load_entity_values(cls, entity):
entity_values = super(Expando, cls)._load_entity_values(entity) for (key, value) in entity.iteritems(): if (key not in entity_values): entity_values[str(key)] = value return entity_values
'Constructor. Args: model_class: Model class from which entities are constructed. keys_only: Whether the query should return full entities or only keys. compile: Whether the query should also return a compiled query. cursor: A compiled query from which to resume. namespace: The namespace to query.'
def __init__(self, model_class=None):
self._model_class = model_class
'Returns whether this query is keys only. Returns: True if this query returns keys, False if it returns entities.'
def is_keys_only(self):
raise NotImplementedError
'Returns the tuple of properties in the projection or None. Projected results differ from normal results in multiple ways: - they only contain a portion of the original entity and cannot be put; - properties defined on the model, but not included in the projections will have a value of None, even if the property is req...
def projection(self):
raise NotImplementedError
'Returns true if the projection query should be distinct. This is equivalent to the SQL syntax: SELECT DISTINCT. It is only available for projection queries, it is not valid to specify distinct without also specifying projection properties. Distinct projection queries on entities with multi-valued properties will retur...
def is_distinct(self):
raise NotImplementedError
'Subclass must override (and not call their super method). Returns: A datastore.Query instance representing the query.'
def _get_query(self):
raise NotImplementedError
'Iterator for this query. If you know the number of results you need, use run(limit=...) instead, or use a GQL query with a LIMIT clause. It\'s more efficient. If you want all results use run(batch_size=<large number>). Args: kwargs: Any keyword arguments accepted by datastore_query.QueryOptions(). Returns: Iterator fo...
def run(self, **kwargs):
raw_query = self._get_query() iterator = raw_query.Run(**kwargs) self._last_raw_query = raw_query keys_only = kwargs.get('keys_only') if (keys_only is None): keys_only = self.is_keys_only() if keys_only: return iterator else: return _QueryIterator(self._model_class, i...
'Iterator for this query. If you know the number of results you need, consider fetch() instead, or use a GQL query with a LIMIT clause. It\'s more efficient.'
def __iter__(self):
return self.run()
'Get first result from this. Beware: get() ignores the LIMIT clause on GQL queries. Args: kwargs: Any keyword arguments accepted by datastore_query.QueryOptions(). Returns: First result from running the query if there are any, else None.'
def get(self, **kwargs):
results = self.run(limit=1, **kwargs) try: return results.next() except StopIteration: return None
'Number of entities this query fetches. Beware: count() ignores the LIMIT clause on GQL queries. Args: limit: A number. If there are more results than this, stop short and just return this number. Providing this argument makes the count operation more efficient. kwargs: Any keyword arguments accepted by datastore_query...
def count(self, limit=1000, **kwargs):
raw_query = self._get_query() result = raw_query.Count(limit=limit, **kwargs) self._last_raw_query = raw_query return result
'Return a list of items selected using SQL-like limit and offset. Always use run(limit=...) instead of fetch() when iterating over a query. Beware: offset must read and discard all skipped entities. Use cursor()/with_cursor() instead. Args: limit: Maximum number of results to return. offset: Optional number of results ...
def fetch(self, limit, offset=0, **kwargs):
if (limit is None): kwargs.setdefault('batch_size', datastore._MAX_INT_32) return list(self.run(limit=limit, offset=offset, **kwargs))
'Get the index list for an already executed query. Returns: A list of indexes used by the query. Raises: AssertionError: If the query has not been executed.'
def index_list(self):
if (self._last_raw_query is None): raise AssertionError('No index list because query has not been run.') if (self._last_index_list is None): raw_index_list = self._last_raw_query.GetIndexList() self._last_index_list = [_index_converter(raw_index) for raw_index in ...
'Get a serialized cursor for an already executed query. The returned cursor effectively lets a future invocation of a similar query to begin fetching results immediately after the last returned result from this query invocation. Returns: A base64-encoded serialized cursor. Raises: AssertionError: If the query has not b...
def cursor(self):
if (self._last_raw_query is None): raise AssertionError('No cursor available.') cursor = self._last_raw_query.GetCursor() return websafe_encode_cursor(cursor)
'Set the start and end of this query using serialized cursors. Conceptually cursors point to the position between the last result returned and the next result so running a query with each of the following cursors combinations will return all results in four chunks with no duplicate results: query.with_cursor(end_cursor...
def with_cursor(self, start_cursor=None, end_cursor=None):
if (start_cursor is None): self._cursor = None else: self._cursor = websafe_decode_cursor(start_cursor) if (end_cursor is None): self._end_cursor = None else: self._end_cursor = websafe_decode_cursor(end_cursor) return self
'Support for query[index] and query[start:stop]. Beware: this ignores the LIMIT clause on GQL queries. Args: arg: Either a single integer, corresponding to the query[index] syntax, or a Python slice object, corresponding to the query[start:stop] or query[start:stop:step] syntax. Returns: A single Model instance when th...
def __getitem__(self, arg):
if isinstance(arg, slice): (start, stop, step) = (arg.start, arg.stop, arg.step) if (start is None): start = 0 if (stop is None): raise ValueError('Open-ended slices are not supported') if (step is None): step = 1 if ((start < 0...
'Iterator constructor Args: model_class: Model class from which entities are constructed. datastore_iterator: Underlying datastore iterator.'
def __init__(self, model_class, datastore_iterator):
self.__model_class = model_class self.__iterator = datastore_iterator
'Iterator on self. Returns: Self.'
def __iter__(self):
return self
'Get next Model instance in query results. Returns: Next model instance. Raises: StopIteration when there are no more results in query.'
def next(self):
if (self.__model_class is not None): return self.__model_class.from_entity(self.__iterator.next()) else: while True: entity = self.__iterator.next() try: model_class = class_for_kind(entity.kind()) except KindError: if datastore...
'Constructs a query over instances of the given Model. Args: model_class: Model class to build query for. keys_only: Whether the query should return full entities or only keys. projection: A tuple of strings representing the property names to include in the projection this query should produce or None. Setting a projec...
def __init__(self, model_class=None, keys_only=False, cursor=None, namespace=None, _app=None, distinct=False, projection=None):
super(Query, self).__init__(model_class) if keys_only: self._keys_only = True if projection: self._projection = projection if (namespace is not None): self._namespace = namespace if (_app is not None): self._app = _app if distinct: self._distinct = True ...
'Add a disjunction of several filters and several values to the query. This is implemented by duplicating queries and combining the results later. Args: operations: a string or list of strings. Each string contains a property name and an operator to filter by. The operators themselves must not require multiple queries ...
def __filter_disjunction(self, operations, values):
if (not isinstance(operations, (list, tuple))): operations = [operations] if (not isinstance(values, (list, tuple))): values = [values] new_query_sets = [] for operation in operations: if (operation.lower().endswith('in') or operation.endswith('!=')): raise BadQueryEr...
'Add filter to query. Args: property_operator: string with the property and operator to filter by. value: the filter value. Returns: Self to support method chaining. Raises: PropertyError if invalid property is provided.'
def filter(self, property_operator, value):
match = _FILTER_REGEX.match(property_operator) prop = match.group(1) if (match.group(3) is not None): operator = match.group(3) else: operator = '==' if (self._model_class is None): if (prop != datastore_types.KEY_SPECIAL_PROPERTY): raise BadQueryError(('Only %...
'Set order of query result. To use descending order, prepend \'-\' (minus) to the property name, e.g., \'-date\' rather than \'date\'. Args: property: Property to sort on. Returns: Self to support method chaining. Raises: PropertyError if invalid property is provided.'
def order(self, property):
if property.startswith('-'): property = property[1:] order = datastore.Query.DESCENDING else: order = datastore.Query.ASCENDING if (self._model_class is None): if ((property != datastore_types.KEY_SPECIAL_PROPERTY) or (order != datastore.Query.ASCENDING)): raise B...
'Sets an ancestor for this query. This restricts the query to only return results that descend from a given model instance. In other words, all of the results will have the ancestor as their parent, or parent\'s parent, etc. The ancestor itself is also a possible result! Args: ancestor: Model or Key (that has already ...
def ancestor(self, ancestor):
if isinstance(ancestor, datastore.Key): if ancestor.has_id_or_name(): self.__ancestor = ancestor else: raise NotSavedError() elif isinstance(ancestor, Model): if ancestor.has_key(): self.__ancestor = ancestor.key() else: raise NotSa...
'Constructor. Args: query_string: Properly formatted GQL query string. *args: Positional arguments used to bind numeric references in the query. **kwds: Dictionary-based arguments for named references. Raises: PropertyError if the query filters or sorts on a property that\'s not indexed.'
def __init__(self, query_string, *args, **kwds):
from google.appengine.ext import gql app = kwds.pop('_app', None) namespace = None if isinstance(app, tuple): if (len(app) != 2): raise BadArgumentError('_app must have 2 values if type is tuple.') (app, namespace) = app self._proto_query = gql.GQL...
'Bind arguments (positional or keyword) to the query. Note that you can also pass arguments directly to the query constructor. Each time you call bind() the previous set of arguments is replaced with the new set. This is useful because the hard work in in parsing the query; so if you expect to be using the same query...
def bind(self, *args, **kwds):
self._args = [] for arg in args: self._args.append(_normalize_query_parameter(arg)) self._kwds = {} for (name, arg) in kwds.iteritems(): self._kwds[name] = _normalize_query_parameter(arg)
'Iterator for this query that handles the LIMIT clause property. If the GQL query string contains a LIMIT clause, this function fetches all results before returning an iterator. Otherwise results are retrieved in batches by the iterator. Args: kwargs: Any keyword arguments accepted by datastore_query.QueryOptions(). Re...
def run(self, **kwargs):
if (self._proto_query.limit() > 0): kwargs.setdefault('limit', self._proto_query.limit()) kwargs.setdefault('offset', self._proto_query.offset()) return _BaseQuery.run(self, **kwargs)
'Construct property. See the Property class for details. Raises: ConfigurationError if indexed=True.'
def __init__(self, *args, **kwds):
self._require_parameter(kwds, 'indexed', False) kwds['indexed'] = True super(UnindexedProperty, self).__init__(*args, **kwds)
'Validate property. Returns: A valid value. Raises: BadValueError if property is not an instance of data_type.'
def validate(self, value):
if ((value is not None) and (not isinstance(value, self.data_type))): try: value = self.data_type(value) except TypeError as err: raise BadValueError(('Property %s must be convertible to a %s instance (%s)' % (self.name, self.data_type.__name__, err...
'Construct string property. Args: verbose_name: Verbose name is always first parameter. multi-line: Carriage returns permitted in property.'
def __init__(self, verbose_name=None, multiline=False, **kwds):
super(StringProperty, self).__init__(verbose_name, **kwds) self.multiline = multiline
'Validate string property. Returns: A valid value. Raises: BadValueError if property is not multi-line but value is.'
def validate(self, value):
value = super(StringProperty, self).validate(value) if ((value is not None) and (not isinstance(value, basestring))): raise BadValueError(('Property %s must be a str or unicode instance, not a %s' % (self.name, type(value).__name__))) if ((not self.multiline) and val...
'Coerce values (except None) to self.data_type. Args: value: The value to be validated and coerced. Returns: The coerced and validated value. It is guaranteed that this is either None or an instance of self.data_type; otherwise an exception is raised. Raises: BadValueError if the value could not be validated or coerce...
def validate(self, value):
value = super(_CoercingProperty, self).validate(value) if ((value is not None) and (not isinstance(value, self.data_type))): value = self.data_type(value) return value
'Validate ByteString property. Returns: A valid value. Raises: BadValueError if property is not instance of \'ByteString\'.'
def validate(self, value):
if ((value is not None) and (not isinstance(value, ByteString))): try: value = ByteString(value) except TypeError as err: raise BadValueError(('Property %s must be convertible to a ByteString instance (%s)' % (self.name, err))) value = super(Byt...
'Construct a DateTimeProperty Args: verbose_name: Verbose name is always first parameter. auto_now: Date/time property is updated with the current time every time it is saved to the datastore. Useful for properties that want to track the modification time of an instance. auto_now_add: Date/time is set to the when its ...
def __init__(self, verbose_name=None, auto_now=False, auto_now_add=False, **kwds):
super(DateTimeProperty, self).__init__(verbose_name, **kwds) self.auto_now = auto_now self.auto_now_add = auto_now_add
'Validate datetime. Returns: A valid value. Raises: BadValueError if property is not instance of \'datetime\'.'
def validate(self, value):
value = super(DateTimeProperty, self).validate(value) if (value and (not isinstance(value, self.data_type))): raise BadValueError(('Property %s must be a %s, but was %r' % (self.name, self.data_type.__name__, value))) return value
'Default value for datetime. Returns: value of now() as appropriate to the date-time instance if auto_now or auto_now_add is set, else user configured default value implementation.'
def default_value(self):
if (self.auto_now or self.auto_now_add): return self.now() return Property.default_value(self)
'Get new value for property to send to datastore. Returns: now() as appropriate to the date-time instance in the odd case where auto_now is set to True, else AUTO_UPDATE_UNCHANGED.'
def get_updated_value_for_datastore(self, model_instance):
if self.auto_now: return self.now() return AUTO_UPDATE_UNCHANGED
'Get now as a full datetime value. Returns: \'now\' as a whole timestamp, including both time and date.'
@staticmethod def now():
return datetime.datetime.now()
'Get now as a date datetime value. Returns: \'date\' part of \'now\' only.'
@staticmethod def now():
return datetime.datetime.now().date()
'Validate date. Returns: A valid value. Raises: BadValueError if property is not instance of \'date\', or if it is an instance of \'datetime\' (which is a subclass of \'date\', but for all practical purposes a different type).'
def validate(self, value):
value = super(DateProperty, self).validate(value) if isinstance(value, datetime.datetime): raise BadValueError(('Property %s must be a %s, not a datetime' % (self.name, self.data_type.__name__))) return value
'Get new value for property to send to datastore. Returns: now() as appropriate to the date instance in the odd case where auto_now is set to True, else AUTO_UPDATE_UNCHANGED.'
def get_updated_value_for_datastore(self, model_instance):
if self.auto_now: return _date_to_datetime(self.now()) return AUTO_UPDATE_UNCHANGED
'Get value from property to send to datastore. We retrieve a datetime.date from the model instance and return a datetime.datetime instance with the time set to zero. See base class method documentation for details.'
def get_value_for_datastore(self, model_instance):
value = super(DateProperty, self).get_value_for_datastore(model_instance) if (value is not None): assert isinstance(value, datetime.date) value = _date_to_datetime(value) return value
'Native representation of this property. We receive a datetime.datetime retrieved from the entity and return a datetime.date instance representing its date portion. See base class method documentation for details.'
def make_value_from_datastore(self, value):
if (value is not None): assert isinstance(value, datetime.datetime) value = value.date() return value
'Get now as a time datetime value. Returns: \'time\' part of \'now\' only.'
@staticmethod def now():
return datetime.datetime.now().time()
'Is time property empty. "0:0" (midnight) is not an empty value. Returns: True if value is None, else False.'
def empty(self, value):
return (value is None)
'Get new value for property to send to datastore. Returns: now() as appropriate to the time instance in the odd case where auto_now is set to True, else AUTO_UPDATE_UNCHANGED.'
def get_updated_value_for_datastore(self, model_instance):
if self.auto_now: return _time_to_datetime(self.now()) return AUTO_UPDATE_UNCHANGED
'Get value from property to send to datastore. We retrieve a datetime.time from the model instance and return a datetime.datetime instance with the date set to 1/1/1970. See base class method documentation for details.'
def get_value_for_datastore(self, model_instance):
value = super(TimeProperty, self).get_value_for_datastore(model_instance) if (value is not None): assert isinstance(value, datetime.time), repr(value) value = _time_to_datetime(value) return value
'Native representation of this property. We receive a datetime.datetime retrieved from the entity and return a datetime.date instance representing its time portion. See base class method documentation for details.'
def make_value_from_datastore(self, value):
if (value is not None): assert isinstance(value, datetime.datetime) value = value.time() return value
'Validate integer property. Returns: A valid value. Raises: BadValueError if value is not an integer or long instance.'
def validate(self, value):
value = super(IntegerProperty, self).validate(value) if (value is None): return value if ((not isinstance(value, (int, long))) or isinstance(value, bool)): raise BadValueError(('Property %s must be an int or long, not a %s' % (self.name, type(value).__name__))) ...
'Is integer property empty. 0 is not an empty value. Returns: True if value is None, else False.'
def empty(self, value):
return (value is None)
'Validate float. Returns: A valid value. Raises: BadValueError if property is not instance of \'float\'.'
def validate(self, value):
value = super(FloatProperty, self).validate(value) if ((value is not None) and (not isinstance(value, float))): raise BadValueError(('Property %s must be a float' % self.name)) return value
'Is float property empty. 0.0 is not an empty value. Returns: True if value is None, else False.'
def empty(self, value):
return (value is None)
'Validate boolean. Returns: A valid value. Raises: BadValueError if property is not instance of \'bool\'.'
def validate(self, value):
value = super(BooleanProperty, self).validate(value) if ((value is not None) and (not isinstance(value, bool))): raise BadValueError(('Property %s must be a bool' % self.name)) return value
'Is boolean property empty. False is not an empty value. Returns: True if value is None, else False.'
def empty(self, value):
return (value is None)
'Initializes this Property with the given options. Note: this does *not* support the \'default\' keyword argument. Use auto_current_user_add=True instead. Args: verbose_name: User friendly name of property. name: Storage name for property. By default, uses attribute name as it is assigned in the Model sub-class. requi...
def __init__(self, verbose_name=None, name=None, required=False, validator=None, choices=None, auto_current_user=False, auto_current_user_add=False, indexed=True):
super(UserProperty, self).__init__(verbose_name, name, required=required, validator=validator, choices=choices, indexed=indexed) self.auto_current_user = auto_current_user self.auto_current_user_add = auto_current_user_add
'Validate user. Returns: A valid value. Raises: BadValueError if property is not instance of \'User\'.'
def validate(self, value):
value = super(UserProperty, self).validate(value) if ((value is not None) and (not isinstance(value, users.User))): raise BadValueError(('Property %s must be a User' % self.name)) return value
'Default value for user. Returns: Value of users.get_current_user() if auto_current_user or auto_current_user_add is set; else None. (But *not* the default implementation, since we don\'t support the \'default\' keyword argument.)'
def default_value(self):
if (self.auto_current_user or self.auto_current_user_add): return users.get_current_user() return None
'Get new value for property to send to datastore. Returns: Value of users.get_current_user() if auto_current_user is set; else AUTO_UPDATE_UNCHANGED.'
def get_updated_value_for_datastore(self, model_instance):
if self.auto_current_user: return users.get_current_user() return AUTO_UPDATE_UNCHANGED
'Construct ListProperty. Args: item_type: Type for the list items; must be one of the allowed property types. verbose_name: Optional verbose name. default: Optional default value; if omitted, an empty list is used. **kwds: Optional additional keyword arguments, passed to base class. Note that the only permissible value...
def __init__(self, item_type, verbose_name=None, default=None, **kwds):
if (item_type is str): item_type = basestring if (not isinstance(item_type, type)): raise TypeError('Item type should be a type object') if (item_type not in _ALLOWED_PROPERTY_TYPES): raise ValueError(('Item type %s is not acceptable' % item_type.__na...
'Validate list. Returns: A valid value. Raises: BadValueError if property is not a list whose items are instances of the item_type given to the constructor.'
def validate(self, value):
value = super(ListProperty, self).validate(value) if (value is not None): if (not isinstance(value, list)): raise BadValueError(('Property %s must be a list' % self.name)) value = self.validate_list_contents(value) return value
'Validates that all items in the list are of the correct type. Returns: The validated list. Raises: BadValueError if the list has items are not instances of the item_type given to the constructor.'
def validate_list_contents(self, value):
if (self.item_type in (int, long)): item_type = (int, long) else: item_type = self.item_type for item in value: if (not isinstance(item, item_type)): if (item_type == (int, long)): raise BadValueError(('Items in the %s list must all be...
'Is list property empty. [] is not an empty value. Returns: True if value is None, else false.'
def empty(self, value):
return (value is None)
'Default value for list. Because the property supplied to \'default\' is a static value, that value must be shallow copied to prevent all fields with default values from sharing the same instance. Returns: Copy of the default value.'
def default_value(self):
return list(super(ListProperty, self).default_value())
'Get value from property to send to datastore. Returns: validated list appropriate to save in the datastore.'
def get_value_for_datastore(self, model_instance):
value = super(ListProperty, self).get_value_for_datastore(model_instance) if (not value): return value value = self.validate_list_contents(value) if self.validator: self.validator(value) if (self.item_type == datetime.date): value = map(_date_to_datetime, value) elif (sel...
'Native representation of this property. If this list is a list of datetime.date or datetime.time, we convert the list of datetime.datetime retrieved from the entity into datetime.date or datetime.time. See base class method documentation for details.'
def make_value_from_datastore(self, value):
if (self.item_type == datetime.date): for v in value: assert isinstance(v, datetime.datetime) value = map((lambda x: x.date()), value) elif (self.item_type == datetime.time): for v in value: assert isinstance(v, datetime.datetime) value = map((lambda x: x....
'Construct StringListProperty. Args: verbose_name: Optional verbose name. default: Optional default value; if omitted, an empty list is used. **kwds: Optional additional keyword arguments, passed to ListProperty().'
def __init__(self, verbose_name=None, default=None, **kwds):
super(StringListProperty, self).__init__(basestring, verbose_name=verbose_name, default=default, **kwds)
'Construct ReferenceProperty. Args: reference_class: Which model class this property references. verbose_name: User friendly name of property. collection_name: If provided, alternate name of collection on reference_class to store back references. Use this to allow a Model to have multiple fields which refer to the sam...
def __init__(self, reference_class=None, verbose_name=None, collection_name=None, **attrs):
super(ReferenceProperty, self).__init__(verbose_name, **attrs) self.collection_name = collection_name if (reference_class is None): reference_class = Model if (not ((isinstance(reference_class, type) and issubclass(reference_class, Model)) or (reference_class is _SELF_REFERENCE))): raise...
'Loads all of the references that point to this model. We need to do this to create the ReverseReferenceProperty properties for this model and create the <reference>_set attributes on the referenced model, e.g.: class Story(db.Model): title = db.StringProperty() class Comment(db.Model): story = db.ReferenceProperty(Sto...
def __property_config__(self, model_class, property_name):
super(ReferenceProperty, self).__property_config__(model_class, property_name) if (self.reference_class is _SELF_REFERENCE): self.reference_class = self.data_type = model_class if (self.collection_name is None): self.collection_name = ('%s_set' % model_class.__name__.lower()) existing_pr...
'Get reference object. This method will fetch unresolved entities from the datastore if they are not already loaded. Returns: ReferenceProperty to Model object if property is set, else None. Raises: ReferencePropertyResolveError: if the referenced model does not exist.'
def __get__(self, model_instance, model_class):
if (model_instance is None): return self if hasattr(model_instance, self.__id_attr_name()): reference_id = getattr(model_instance, self.__id_attr_name()) else: reference_id = None if (reference_id is not None): resolved = getattr(model_instance, self.__resolved_attr_name(...
'Set reference.'
def __set__(self, model_instance, value):
value = self.validate(value) if (value is not None): if isinstance(value, datastore.Key): setattr(model_instance, self.__id_attr_name(), value) setattr(model_instance, self.__resolved_attr_name(), None) else: setattr(model_instance, self.__id_attr_name(), valu...
'Get key of reference rather than reference itself.'
def get_value_for_datastore(self, model_instance):
return getattr(model_instance, self.__id_attr_name())
'Validate reference. Returns: A valid value. Raises: BadValueError for the following reasons: - Value is not saved. - Object not of correct model type for reference.'
def validate(self, value):
if isinstance(value, datastore.Key): return value if ((value is not None) and (not value.has_key())): raise BadValueError(('%s instance must have a complete key before it can be stored as a reference' % self.reference_class.kind())) value = super(Ref...
'Get attribute of referenced id. Returns: Attribute where to store id of referenced entity.'
def __id_attr_name(self):
return self._attr_name()
'Get attribute of resolved attribute. The resolved attribute is where the actual loaded reference instance is stored on the referring model instance. Returns: Attribute name of where to store resolved reference model instance.'
def __resolved_attr_name(self):
return ('_RESOLVED' + self._attr_name())