Python google.appengine.ext.db.Model() Examples

The following are 30 code examples of google.appengine.ext.db.Model(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module google.appengine.ext.db , or try the search function .
Example #1
Source File: metadata.py    From python-compat-runtime with Apache License 2.0 6 votes vote down vote up
def key_for_entity(cls, entity_or_key):
    """Return the metadata key for the entity group containing entity_or_key.

    Use this key to get() the __entity_group__ metadata entity for the
    entity group containing entity_or_key.

    Args:
      entity_or_key: a key or entity whose __entity_group__ key you want.

    Returns:
      The __entity_group__ key for the entity group containing entity_or_key.
    """
    if isinstance(entity_or_key, db.Model):
      key = entity_or_key.key()
    else:
      key = entity_or_key
    while key.parent():
      key = key.parent()
    return db.Key.from_path(cls.KIND_NAME, cls.ID, parent=key) 
Example #2
Source File: property_range.py    From python-compat-runtime with Apache License 2.0 6 votes vote down vote up
def make_query(self, ns):
    """Make a query of entities within this range.

    Query options are not supported. They should be specified when the query
    is run.

    Args:
      ns: namespace of this query.

    Returns:
      a db.Query or ndb.Query, depends on the model class's type.
    """
    if issubclass(self.model_class, db.Model):
      query = db.Query(self.model_class, namespace=ns)
      for f in self.filters:
        query.filter("%s %s" % (f[0], f[1]), f[2])
    else:
      query = self.model_class.query(namespace=ns)
      for f in self.filters:
        query = query.filter(ndb.FilterNode(*f))
    return query 
Example #3
Source File: input_readers.py    From python-compat-runtime with Apache License 2.0 6 votes vote down vote up
def _validate_filters_ndb(cls, filters, model_class):
    """Validate ndb.Model filters."""
    if not filters:
      return

    properties = model_class._properties

    for f in filters:
      prop, _, val = f
      if prop not in properties:
        raise errors.BadReaderParamsError(
            "Property %s is not defined for entity type %s",
            prop, model_class._get_kind())



      try:
        properties[prop]._do_validate(val)
      except db.BadValueError, e:
        raise errors.BadReaderParamsError(e) 
Example #4
Source File: pager.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def __init__(self, model_class, keys_only=False):
        """Constructs a bookmarkable 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.
        """
        # Initialize query values.
        self._model_class = model_class
        self._keys_only = keys_only
        self._ancestor = None
        self._filters = {}
        self._inequality_prop = None
        self._inequality_filters = {}
        self._orderings = []
        self._order_directions = {}
        # Properties that should be encoded into a bookmark: inequalities
        # and orderings.
        self._bookmark_properties = []
        # Keep track of first result to know when we are on first page.
        self._first_result = None 
Example #5
Source File: appengine.py    From earthengine with MIT License 6 votes vote down vote up
def __init__(self, model, key_name, property_name, cache=None, user=None):
    """Constructor for Storage.

    Args:
      model: db.Model or ndb.Model, model class
      key_name: string, key name for the entity that has the credentials
      property_name: string, name of the property that is a CredentialsProperty
        or CredentialsNDBProperty.
      cache: memcache, a write-through cache to put in front of the datastore.
        If the model you are using is an NDB model, using a cache will be
        redundant since the model uses an instance cache and memcache for you.
      user: users.User object, optional. Can be used to grab user ID as a
        key_name if no key name is specified.
    """
    if key_name is None:
      if user is None:
        raise ValueError('StorageByKeyName called with no key name or user.')
      key_name = user.user_id()

    self._model = model
    self._key_name = key_name
    self._property_name = property_name
    self._cache = cache 
Example #6
Source File: property_range.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def make_query(self, ns):
    """Make a query of entities within this range.

    Query options are not supported. They should be specified when the query
    is run.

    Args:
      ns: namespace of this query.

    Returns:
      a db.Query or ndb.Query, depends on the model class's type.
    """
    if issubclass(self.model_class, db.Model):
      query = db.Query(self.model_class, namespace=ns)
      for f in self.filters:
        query.filter("%s %s" % (f[0], f[1]), f[2])
    else:
      query = self.model_class.query(namespace=ns)
      for f in self.filters:
        query = query.filter(ndb.FilterNode(*f))
    return query 
Example #7
Source File: __init__.py    From python-compat-runtime with Apache License 2.0 6 votes vote down vote up
def make_ascending_query(self, kind_class, keys_only=False, filters=None):
    """Construct a query for this key range without setting the scan direction.

    Args:
      kind_class: A kind implementation class (a subclass of either
        db.Model or ndb.Model).
      keys_only: bool, default False, query only for keys.
      filters: optional list of filters to apply to the query. Each filter is
        a tuple: (<property_name_as_str>, <query_operation_as_str>, <value>).
        User filters are applied first.

    Returns:
      A db.Query or ndb.Query instance (corresponding to kind_class).
    """
    if ndb is not None:
      if issubclass(kind_class, ndb.Model):
        return self.make_ascending_ndb_query(
            kind_class, keys_only=keys_only, filters=filters)
    assert self._app is None, '_app is not supported for db.Query'
    query = db.Query(kind_class, namespace=self.namespace, keys_only=keys_only)
    query.order("__key__")

    query = self.filter_query(query, filters=filters)
    return query 
Example #8
Source File: cache.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def _read(self, key = None):
        """
        _read returns a cache object determined by the key. It's set
        to private because it returns a db.Model object, and also
        does not handle the unpickling of objects making it not the
        best candidate for use. The special method __getitem__ is the
        preferred access method for cache data.
        """
        query = _AppEngineUtilities_Cache.all()
        query.filter('cachekey', key)
        query.filter('timeout > ', datetime.datetime.now())
        results = query.fetch(1)
        if len(results) is 0:
            return None
        return results[0]

        if 'AEU_Events' in __main__.__dict__:
            __main__.AEU_Events.fire_event('cacheReadFromDatastore')
        if 'AEU_Events' in __main__.__dict__:
            __main__.AEU_Events.fire_event('cacheRead') 
Example #9
Source File: bulkloader.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def handle_entity(self, entity):
    """Subclasses can override this to add custom entity conversion code.

    This is called for each entity, after its properties are populated
    from the input but before it is stored. Subclasses can override
    this to add custom entity handling code.

    The entity to be inserted should be returned. If multiple entities
    should be inserted, return a list of entities. If no entities
    should be inserted, return None or [].

    Args:
      entity: db.Model

    Returns:
      db.Model or list of db.Model
    """
    return entity 
Example #10
Source File: __init__.py    From python-compat-runtime with Apache License 2.0 6 votes vote down vote up
def make_ascending_ndb_query(self, kind_class, keys_only=False, filters=None):
    """Construct an NDB query for this key range, without the scan direction.

    Args:
      kind_class: An ndb.Model subclass.
      keys_only: bool, default False, query only for keys.

    Returns:
      An ndb.Query instance.
    """
    assert issubclass(kind_class, ndb.Model)
    if keys_only:
      default_options = ndb.QueryOptions(keys_only=True)
    else:
      default_options = None
    query = kind_class.query(app=self._app,
                             namespace=self.namespace,
                             default_options=default_options)
    query = self.filter_ndb_query(query, filters=filters)
    query = query.order(kind_class._key)
    return query 
Example #11
Source File: bulkloader.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def GetImplementationClass(kind_or_class_key):
  """Returns the implementation class for a given kind or class key.

  Args:
    kind_or_class_key: A kind string or a tuple of kind strings.

  Return:
    A db.Model subclass for the given kind or class key.
  """
  if isinstance(kind_or_class_key, tuple):
    try:
      implementation_class = polymodel._class_map[kind_or_class_key]
    except KeyError:
      raise db.KindError('No implementation for class \'%s\'' %
                         kind_or_class_key)
  else:
    implementation_class = db.class_for_kind(kind_or_class_key)
  return implementation_class 
Example #12
Source File: input_readers.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def _validate_filters_ndb(cls, filters, model_class):
    """Validate ndb.Model filters."""
    if not filters:
      return

    properties = model_class._properties

    for f in filters:
      prop, _, val = f
      if prop not in properties:
        raise errors.BadReaderParamsError(
            "Property %s is not defined for entity type %s",
            prop, model_class._get_kind())

      # Validate the value of each filter. We need to know filters have
      # valid value to carry out splits.
      try:
        properties[prop]._do_validate(val)
      except db.BadValueError, e:
        raise errors.BadReaderParamsError(e) 
Example #13
Source File: __init__.py    From python-compat-runtime with Apache License 2.0 6 votes vote down vote up
def make_directed_query(self, kind_class, keys_only=False):
    """Construct a query for this key range, including the scan direction.

    Args:
      kind_class: A kind implementation class (a subclass of either
        db.Model or ndb.Model).
      keys_only: bool, default False, use keys_only on Query?

    Returns:
      A db.Query or ndb.Query instance (corresponding to kind_class).

    Raises:
      KeyRangeError: if self.direction is not in (KeyRange.ASC, KeyRange.DESC).
    """
    if ndb is not None:
      if issubclass(kind_class, ndb.Model):
        return self.make_directed_ndb_query(kind_class, keys_only=keys_only)
    assert self._app is None, '_app is not supported for db.Query'
    direction = self.__get_direction("", "-")
    query = db.Query(kind_class, namespace=self.namespace, keys_only=keys_only)
    query.order("%s__key__" % direction)

    query = self.filter_query(query)
    return query 
Example #14
Source File: model_datastore_input_reader.py    From python-compat-runtime with Apache License 2.0 6 votes vote down vote up
def _validate_filters_ndb(cls, filters, model_class):
    """Validate ndb.Model filters."""
    if not filters:
      return

    properties = model_class._properties

    for f in filters:
      prop, _, val = f
      if prop not in properties:
        raise errors.BadReaderParamsError(
            "Property %s is not defined for entity type %s",
            prop, model_class._get_kind())



      try:
        properties[prop]._do_validate(val)
      except db.BadValueError, e:
        raise errors.BadReaderParamsError(e) 
Example #15
Source File: model_datastore_input_reader.py    From locality-sensitive-hashing with MIT License 6 votes vote down vote up
def _validate_filters_ndb(cls, filters, model_class):
    """Validate ndb.Model filters."""
    if not filters:
      return

    properties = model_class._properties

    for f in filters:
      prop, _, val = f
      if prop not in properties:
        raise errors.BadReaderParamsError(
            "Property %s is not defined for entity type %s",
            prop, model_class._get_kind())

      # Validate the value of each filter. We need to know filters have
      # valid value to carry out splits.
      try:
        properties[prop]._do_validate(val)
      except db.BadValueError, e:
        raise errors.BadReaderParamsError(e) 
Example #16
Source File: pager.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def ancestor(self, ancestor):
        """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 been saved)

        Returns:
          Self to support method chaining.
        """
        self._ancestor = ancestor
        return self 
Example #17
Source File: input_readers.py    From locality-sensitive-hashing with MIT License 6 votes vote down vote up
def _validate_filters_ndb(cls, filters, model_class):
    """Validate ndb.Model filters."""
    if not filters:
      return

    properties = model_class._properties

    for f in filters:
      prop, _, val = f
      if prop not in properties:
        raise errors.BadReaderParamsError(
            "Property %s is not defined for entity type %s",
            prop, model_class._get_kind())

      # Validate the value of each filter. We need to know filters have
      # valid value to carry out splits.
      try:
        properties[prop]._do_validate(val)
      except db.BadValueError, e:
        raise errors.BadReaderParamsError(e) 
Example #18
Source File: appengine.py    From splunk-ref-pas-code with Apache License 2.0 6 votes vote down vote up
def __init__(self, model, key_name, property_name, cache=None, user=None):
    """Constructor for Storage.

    Args:
      model: db.Model or ndb.Model, model class
      key_name: string, key name for the entity that has the credentials
      property_name: string, name of the property that is a CredentialsProperty
        or CredentialsNDBProperty.
      cache: memcache, a write-through cache to put in front of the datastore.
        If the model you are using is an NDB model, using a cache will be
        redundant since the model uses an instance cache and memcache for you.
      user: users.User object, optional. Can be used to grab user ID as a
        key_name if no key name is specified.
    """
    if key_name is None:
      if user is None:
        raise ValueError('StorageByKeyName called with no key name or user.')
      key_name = user.user_id()

    self._model = model
    self._key_name = key_name
    self._property_name = property_name
    self._cache = cache 
Example #19
Source File: appengine.py    From sndlatr with Apache License 2.0 6 votes vote down vote up
def __init__(self, model, key_name, property_name, cache=None, user=None):
    """Constructor for Storage.

    Args:
      model: db.Model or ndb.Model, model class
      key_name: string, key name for the entity that has the credentials
      property_name: string, name of the property that is a CredentialsProperty
        or CredentialsNDBProperty.
      cache: memcache, a write-through cache to put in front of the datastore.
        If the model you are using is an NDB model, using a cache will be
        redundant since the model uses an instance cache and memcache for you.
      user: users.User object, optional. Can be used to grab user ID as a
        key_name if no key name is specified.
    """
    if key_name is None:
      if user is None:
        raise ValueError('StorageByKeyName called with no key name or user.')
      key_name = user.user_id()

    self._model = model
    self._key_name = key_name
    self._property_name = property_name
    self._cache = cache 
Example #20
Source File: appengine.py    From billing-export-python with Apache License 2.0 6 votes vote down vote up
def __init__(self, model, key_name, property_name, cache=None, user=None):
    """Constructor for Storage.

    Args:
      model: db.Model or ndb.Model, model class
      key_name: string, key name for the entity that has the credentials
      property_name: string, name of the property that is a CredentialsProperty
        or CredentialsNDBProperty.
      cache: memcache, a write-through cache to put in front of the datastore.
        If the model you are using is an NDB model, using a cache will be
        redundant since the model uses an instance cache and memcache for you.
      user: users.User object, optional. Can be used to grab user ID as a
        key_name if no key name is specified.
    """
    if key_name is None:
      if user is None:
        raise ValueError('StorageByKeyName called with no key name or user.')
      key_name = user.user_id()

    self._model = model
    self._key_name = key_name
    self._property_name = property_name
    self._cache = cache 
Example #21
Source File: bulkloader.py    From python-compat-runtime with Apache License 2.0 6 votes vote down vote up
def handle_entity(self, entity):
    """Subclasses can override this to add custom entity conversion code.

    This is called for each entity, after its properties are populated
    from the input but before it is stored. Subclasses can override
    this to add custom entity handling code.

    The entity to be inserted should be returned. If multiple entities
    should be inserted, return a list of entities. If no entities
    should be inserted, return None or [].

    Args:
      entity: db.Model

    Returns:
      db.Model or list of db.Model
    """
    return entity 
Example #22
Source File: bulkloader.py    From python-compat-runtime with Apache License 2.0 6 votes vote down vote up
def GetImplementationClass(kind_or_class_key):
  """Returns the implementation class for a given kind or class key.

  Args:
    kind_or_class_key: A kind string or a tuple of kind strings.

  Return:
    A db.Model subclass for the given kind or class key.
  """
  if isinstance(kind_or_class_key, tuple):
    try:
      implementation_class = polymodel._class_map[kind_or_class_key]
    except KeyError:
      raise db.KindError('No implementation for class \'%s\'' %
                         kind_or_class_key)
  else:
    implementation_class = db.class_for_kind(kind_or_class_key)
  return implementation_class 
Example #23
Source File: appengine.py    From aqua-monitor with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _is_ndb(self):
        """Determine whether the model of the instance is an NDB model.

        Returns:
            Boolean indicating whether or not the model is an NDB or DB model.
        """
        # issubclass will fail if one of the arguments is not a class, only
        # need worry about new-style classes since ndb and db models are
        # new-style
        if isinstance(self._model, type):
            if _NDB_MODEL is not None and issubclass(self._model, _NDB_MODEL):
                return True
            elif issubclass(self._model, db.Model):
                return False

        raise TypeError('Model class not an NDB or DB model: %s.' %
                        (self._model,)) 
Example #24
Source File: appengine.py    From googleapps-message-recall with Apache License 2.0 6 votes vote down vote up
def __init__(self, model, key_name, property_name, cache=None, user=None):
    """Constructor for Storage.

    Args:
      model: db.Model or ndb.Model, model class
      key_name: string, key name for the entity that has the credentials
      property_name: string, name of the property that is a CredentialsProperty
        or CredentialsNDBProperty.
      cache: memcache, a write-through cache to put in front of the datastore.
        If the model you are using is an NDB model, using a cache will be
        redundant since the model uses an instance cache and memcache for you.
      user: users.User object, optional. Can be used to grab user ID as a
        key_name if no key name is specified.
    """
    if key_name is None:
      if user is None:
        raise ValueError('StorageByKeyName called with no key name or user.')
      key_name = user.user_id()

    self._model = model
    self._key_name = key_name
    self._property_name = property_name
    self._cache = cache 
Example #25
Source File: appengine.py    From twitter-for-bigquery with Apache License 2.0 6 votes vote down vote up
def __init__(self, model, key_name, property_name, cache=None, user=None):
    """Constructor for Storage.

    Args:
      model: db.Model or ndb.Model, model class
      key_name: string, key name for the entity that has the credentials
      property_name: string, name of the property that is a CredentialsProperty
        or CredentialsNDBProperty.
      cache: memcache, a write-through cache to put in front of the datastore.
        If the model you are using is an NDB model, using a cache will be
        redundant since the model uses an instance cache and memcache for you.
      user: users.User object, optional. Can be used to grab user ID as a
        key_name if no key name is specified.
    """
    if key_name is None:
      if user is None:
        raise ValueError('StorageByKeyName called with no key name or user.')
      key_name = user.user_id()

    self._model = model
    self._key_name = key_name
    self._property_name = property_name
    self._cache = cache 
Example #26
Source File: appengine.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def _is_ndb(self):
        """Determine whether the model of the instance is an NDB model.

        Returns:
            Boolean indicating whether or not the model is an NDB or DB model.
        """
        # issubclass will fail if one of the arguments is not a class, only
        # need worry about new-style classes since ndb and db models are
        # new-style
        if isinstance(self._model, type):
            if ndb is not None and issubclass(self._model, ndb.Model):
                return True
            elif issubclass(self._model, db.Model):
                return False

        raise TypeError('Model class not an NDB or DB model: %s.' %
                        (self._model,)) 
Example #27
Source File: appengine.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def _is_ndb(self):
        """Determine whether the model of the instance is an NDB model.

        Returns:
            Boolean indicating whether or not the model is an NDB or DB model.
        """
        # issubclass will fail if one of the arguments is not a class, only
        # need worry about new-style classes since ndb and db models are
        # new-style
        if isinstance(self._model, type):
            if ndb is not None and issubclass(self._model, ndb.Model):
                return True
            elif issubclass(self._model, db.Model):
                return False

        raise TypeError('Model class not an NDB or DB model: %s.' %
                        (self._model,)) 
Example #28
Source File: appengine.py    From alfred-gmail with MIT License 6 votes vote down vote up
def _is_ndb(self):
        """Determine whether the model of the instance is an NDB model.

        Returns:
            Boolean indicating whether or not the model is an NDB or DB model.
        """
        # issubclass will fail if one of the arguments is not a class, only
        # need worry about new-style classes since ndb and db models are
        # new-style
        if isinstance(self._model, type):
            if _NDB_MODEL is not None and issubclass(self._model, _NDB_MODEL):
                return True
            elif issubclass(self._model, db.Model):
                return False

        raise TypeError(
            'Model class not an NDB or DB model: {0}.'.format(self._model)) 
Example #29
Source File: appengine.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def _is_ndb(self):
        """Determine whether the model of the instance is an NDB model.

        Returns:
            Boolean indicating whether or not the model is an NDB or DB model.
        """
        # issubclass will fail if one of the arguments is not a class, only
        # need worry about new-style classes since ndb and db models are
        # new-style
        if isinstance(self._model, type):
            if ndb is not None and issubclass(self._model, ndb.Model):
                return True
            elif issubclass(self._model, db.Model):
                return False

        raise TypeError('Model class not an NDB or DB model: %s.' %
                        (self._model,)) 
Example #30
Source File: appengine.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def _is_ndb(self):
        """Determine whether the model of the instance is an NDB model.

        Returns:
            Boolean indicating whether or not the model is an NDB or DB model.
        """
        # issubclass will fail if one of the arguments is not a class, only
        # need worry about new-style classes since ndb and db models are
        # new-style
        if isinstance(self._model, type):
            if ndb is not None and issubclass(self._model, ndb.Model):
                return True
            elif issubclass(self._model, db.Model):
                return False

        raise TypeError('Model class not an NDB or DB model: %s.' %
                        (self._model,))