Python google.appengine.ext.ndb.ComputedProperty() Examples

The following are 12 code examples of google.appengine.ext.ndb.ComputedProperty(). 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.ndb , or try the search function .
Example #1
Source File: task_result.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def need_update_from_run_result(self, run_result):
    """Returns True if set_from_run_result() would modify this instance.

    E.g. they are different and TaskResultSummary needs to be updated from the
    corresponding TaskRunResult.
    """
    assert isinstance(run_result, TaskRunResult), run_result
    # A previous try is still sending update. Ignore it from a result summary
    # PoV.
    if self.try_number and self.try_number > run_result.try_number:
      return False

    for property_name in _TaskResultCommon._properties_fixed():
      if getattr(self, property_name) != getattr(run_result, property_name):
        return True
    # Include explicit support for 'state' and 'try_number'. TaskRunResult.state
    # is a ComputedProperty so it can't be copied as-is, and try_number is a
    # generated property.
    # pylint: disable=W0201
    return (
        self.state != run_result.state or
        self.try_number != run_result.try_number) 
Example #2
Source File: utils_test.py    From upvote with Apache License 2.0 6 votes vote down vote up
def testHasValue(self):

    class Foo(ndb.Model):
      a = ndb.ComputedProperty(lambda self: 'a')
      b = ndb.StringProperty()

    foo = Foo()
    self.assertFalse(datastore_utils.HasValue(foo, 'a'))
    self.assertFalse(datastore_utils.HasValue(foo, 'b'))

    foo.b = 'b'
    self.assertFalse(datastore_utils.HasValue(foo, 'a'))
    self.assertTrue(datastore_utils.HasValue(foo, 'b'))

    foo.put()
    self.assertTrue(datastore_utils.HasValue(foo, 'a'))
    self.assertTrue(datastore_utils.HasValue(foo, 'b')) 
Example #3
Source File: utils.py    From upvote with Apache License 2.0 6 votes vote down vote up
def GetLocalComputedPropertyValue(entity, computed_property_name):
  """Return the local value of a ComputedProperty instead of re-computing.

  Args:
    entity: ndb.Model, The entity from which the ComputedProperty will be read.
    computed_property_name: str, The name of the ComputedProperty whose value
        will be read.

  Returns:
    The local value of the property.

  Raises:
    PropertyError: The property was not found or was not a ComputedProperty.
  """
  computed_property = entity._properties.get(computed_property_name, None)  # pylint: disable=protected-access
  if not computed_property:
    raise PropertyError('Property %s not found' % computed_property_name)
  elif not isinstance(computed_property, ndb.ComputedProperty):
    raise PropertyError(
        'Property %s is of type %s. Expected ComputedProperty.' % (
            computed_property_name, type(entity).__name__))
  return super(  # pylint: disable=protected-access
      ndb.ComputedProperty, computed_property)._get_value(entity) 
Example #4
Source File: ndb.py    From jbox with MIT License 5 votes vote down vote up
def convert_ComputedProperty(self, model, prop, kwargs):
        """Returns a form field for a ``ndb.ComputedProperty``."""
        return None 
Example #5
Source File: ndb.py    From RSSNewsGAE with Apache License 2.0 5 votes vote down vote up
def convert_ComputedProperty(self, model, prop, kwargs):
        """Returns a form field for a ``ndb.ComputedProperty``."""
        return None 
Example #6
Source File: ndb.py    From googleapps-message-recall with Apache License 2.0 5 votes vote down vote up
def convert_ComputedProperty(self, model, prop, kwargs):
        """Returns a form field for a ``ndb.ComputedProperty``."""
        return None 
Example #7
Source File: task_result.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def _properties_fixed(cls):
    """Returns all properties with their member name, excluding computed
    properties.
    """
    return [
      prop._code_name for prop in cls._properties.values()
      if not isinstance(prop, ndb.ComputedProperty)
    ] 
Example #8
Source File: task_result.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def set_from_run_result(self, run_result, request):
    """Copies all the relevant properties from a TaskRunResult into this
    TaskResultSummary.

    If the task completed, succeeded and is idempotent, self.properties_hash is
    set.
    """
    assert ndb.in_transaction()
    assert isinstance(request, task_request.TaskRequest), request
    assert isinstance(run_result, TaskRunResult), run_result
    for property_name in _TaskResultCommon._properties_fixed():
      setattr(self, property_name, getattr(run_result, property_name))
    # Include explicit support for 'state' and 'try_number'. TaskRunResult.state
    # is a ComputedProperty so it can't be copied as-is, and try_number is a
    # generated property.
    # pylint: disable=W0201
    self.state = run_result.state
    self.try_number = run_result.try_number

    while len(self.costs_usd) < run_result.try_number:
      self.costs_usd.append(0.)
    self.costs_usd[run_result.try_number-1] = run_result.cost_usd

    # Update the automatic tags, removing the ones from the other
    # TaskProperties.
    t = request.task_slice(run_result.current_task_slice or 0)
    if run_result.current_task_slice != self.current_task_slice:
      self.tags = task_request.get_automatic_tags(
          request, run_result.current_task_slice)
    if (self.state == State.COMPLETED and
        not self.failure and
        not self.internal_failure and
        t.properties.idempotent and
        not self.deduped_from):
      # Signal the results are valid and can be reused. If the request has a
      # SecretBytes, it is GET, which is a performance concern.
      self.properties_hash = t.properties_hash(request) 
Example #9
Source File: input_readers.py    From appengine-mapreduce with Apache License 2.0 5 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 idx, f in enumerate(filters):
      prop, ineq, val = f
      if prop not in properties:
        raise errors.BadReaderParamsError(
            "Property %s is not defined for entity type %s",
            prop, model_class._get_kind())

      # Attempt to cast the value to a KeyProperty if appropriate.
      # This enables filtering against keys.
      try:
        if (isinstance(val, basestring) and
            isinstance(properties[prop],
              (ndb.KeyProperty, ndb.ComputedProperty))):
          val = ndb.Key(urlsafe=val)
          filters[idx] = [prop, ineq, val]
      except:
        pass

      # 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 #10
Source File: utils_test.py    From upvote with Apache License 2.0 5 votes vote down vote up
def testFailToSet_ComputedProperty(self):
    class A(ndb.Model):
      a = ndb.StringProperty()
      b = ndb.ComputedProperty(lambda self: self.a[0])

    inst = A(a='xyz')
    inst.put()

    self.assertEqual('x', inst.b)

    with self.assertRaises(datastore_utils.PropertyError):
      datastore_utils.CopyEntity(inst, b='a') 
Example #11
Source File: utils_test.py    From upvote with Apache License 2.0 5 votes vote down vote up
def testModelWithComputedProperty(self):
    class A(ndb.Model):
      a = ndb.StringProperty()
      b = ndb.ComputedProperty(lambda self: self.a[0])

    inst = A(a='xyz')
    inst.put()

    self.assertEqual('x', inst.b)

    new = datastore_utils.CopyEntity(inst, a='abc')
    new.put()

    self.assertEqual('a', new.b) 
Example #12
Source File: utils_test.py    From upvote with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    super(GetLocalComputedPropertyValueTest, self).setUp()

    class A(ndb.Model):
      a = ndb.StringProperty()
      b = ndb.ComputedProperty(lambda self: self.a[0])

    self.inst = A(a='xyz')