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

The following are 30 code examples for showing how to use google.appengine.ext.ndb.StringProperty(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

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
Project: googleapps-message-recall   Author: google   File: recall_task.py    License: Apache License 2.0 6 votes vote down vote up
def SetTaskState(cls, task_key_id, new_state, is_aborted=True):
    """Utility method to update the state of the master task record.

    Args:
      task_key_id: String (serializable) unique id of the task record.
      new_state: String update for the ndb StringProperty field.
      is_aborted: Boolean; False when performing final update.
    """
    task = cls.GetTaskByKey(task_key_id)
    if task:
      if task.task_state != TASK_DONE:
        task.task_state = new_state
        if new_state == TASK_DONE:
          _LOG.warning('RecallTaskModel id=%s Done.', task_key_id)
      task.is_aborted = is_aborted
      task.put() 
Example 2
Project: python-docs-samples   Author: GoogleCloudPlatform   File: snippets.py    License: Apache License 2.0 6 votes vote down vote up
def query_purchase_with_customer_key():
    # [START purchase_with_customer_key_models]
    class Customer(ndb.Model):
        name = ndb.StringProperty()

    class Purchase(ndb.Model):
        customer = ndb.KeyProperty(kind=Customer)
        price = ndb.IntegerProperty()
    # [END purchase_with_customer_key_models]

    def query_purchases_for_customer_via_key(customer_entity):
        purchases = Purchase.query(
            Purchase.customer == customer_entity.key).fetch()
        return purchases

    return Customer, Purchase, query_purchases_for_customer_via_key 
Example 3
Project: python-docs-samples   Author: GoogleCloudPlatform   File: snippets.py    License: Apache License 2.0 6 votes vote down vote up
def query_purchase_with_ancestor_key():
    # [START purchase_with_ancestor_key_models]
    class Customer(ndb.Model):
        name = ndb.StringProperty()

    class Purchase(ndb.Model):
        price = ndb.IntegerProperty()
    # [END purchase_with_ancestor_key_models]

    def create_purchase_for_customer_with_ancestor(customer_entity):
        purchase = Purchase(parent=customer_entity.key)
        return purchase

    def query_for_purchases_of_customer_with_ancestor(customer_entity):
        purchases = Purchase.query(ancestor=customer_entity.key).fetch()
        return purchases

    return (Customer, Purchase,
            create_purchase_for_customer_with_ancestor,
            query_for_purchases_of_customer_with_ancestor) 
Example 4
Project: luci-py   Author: luci   File: config_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_expiration(self):
    self.mock_now(datetime.datetime(2014, 1, 2, 3, 4, 5, 6))

    class Config(config.GlobalConfig):
      param = ndb.StringProperty(default='default')

    # Bootstrap the config.
    Config.cached()

    # fetch-update cycle, necessary to avoid modifying cached copy in-place.
    conf = Config.fetch()
    conf.param = 'new-value'
    conf.store(updated_by='someone')

    # Right before expiration.
    self.mock_now(datetime.datetime(2014, 1, 2, 3, 4, 5, 6), 59)
    self.assertEqual('default', Config.cached().param)

    # After expiration.
    self.mock_now(datetime.datetime(2014, 1, 2, 3, 4, 5, 6), 61)
    self.assertEqual('new-value', Config.cached().param) 
Example 5
Project: luci-py   Author: luci   File: config_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_expiration(self):
    self.mock_now(datetime.datetime(2014, 1, 2, 3, 4, 5, 6))

    class Config(config.GlobalConfig):
      param = ndb.StringProperty(default='default')

    # Bootstrap the config.
    Config.cached()

    # fetch-update cycle, necessary to avoid modifying cached copy in-place.
    conf = Config.fetch()
    conf.param = 'new-value'
    conf.store(updated_by='someone')

    # Right before expiration.
    self.mock_now(datetime.datetime(2014, 1, 2, 3, 4, 5, 6), 59)
    self.assertEqual('default', Config.cached().param)

    # After expiration.
    self.mock_now(datetime.datetime(2014, 1, 2, 3, 4, 5, 6), 61)
    self.assertEqual('new-value', Config.cached().param) 
Example 6
Project: luci-py   Author: luci   File: config_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_expiration(self):
    self.mock_now(datetime.datetime(2014, 1, 2, 3, 4, 5, 6))

    class Config(config.GlobalConfig):
      param = ndb.StringProperty(default='default')

    # Bootstrap the config.
    Config.cached()

    # fetch-update cycle, necessary to avoid modifying cached copy in-place.
    conf = Config.fetch()
    conf.param = 'new-value'
    conf.store(updated_by='someone')

    # Right before expiration.
    self.mock_now(datetime.datetime(2014, 1, 2, 3, 4, 5, 6), 59)
    self.assertEqual('default', Config.cached().param)

    # After expiration.
    self.mock_now(datetime.datetime(2014, 1, 2, 3, 4, 5, 6), 61)
    self.assertEqual('new-value', Config.cached().param) 
Example 7
Project: luci-py   Author: luci   File: config_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_expiration(self):
    self.mock_now(datetime.datetime(2014, 1, 2, 3, 4, 5, 6))

    class Config(config.GlobalConfig):
      param = ndb.StringProperty(default='default')

    # Bootstrap the config.
    Config.cached()

    # fetch-update cycle, necessary to avoid modifying cached copy in-place.
    conf = Config.fetch()
    conf.param = 'new-value'
    conf.store(updated_by='someone')

    # Right before expiration.
    self.mock_now(datetime.datetime(2014, 1, 2, 3, 4, 5, 6), 59)
    self.assertEqual('default', Config.cached().param)

    # After expiration.
    self.mock_now(datetime.datetime(2014, 1, 2, 3, 4, 5, 6), 61)
    self.assertEqual('new-value', Config.cached().param) 
Example 8
Project: upvote   Author: google   File: utils_test.py    License: Apache License 2.0 6 votes vote down vote up
def testSameSchema(self):

    # Initial schema
    class A(ndb.Model):
      a = ndb.StringProperty()
      b = ndb.StringProperty()

    # Create an entity using the initial schema
    inst = A(a='abc', b='def')
    inst.put()

    self.assertIsNotNone(inst.b)

    # Delete the property and save the entity
    datastore_utils.DeleteProperty(inst, 'b')
    inst.put()
    inst = A.get_by_id(inst.key.id())

    # The old data is gone :)
    self.assertIsNone(inst.b) 
Example 9
Project: upvote   Author: google   File: utils_test.py    License: Apache License 2.0 6 votes vote down vote up
def testSameSchema_DoesntDeleteProperty(self):

    # Initial schema
    class A(ndb.Model):
      a = ndb.StringProperty()
      b = ndb.StringProperty()

    # Create an entity using the initial schema
    inst = A(a='abc', b='def')
    inst.put()

    # Delete the property and save the entity
    datastore_utils.DeleteProperty(inst, 'b')
    inst.put()

    # Create a new instance and verify that the 'b' hasn't disappeared
    new = A(a='abc', b='def')
    new.put()
    self.assertTrue(datastore_utils.HasProperty(new, 'b')) 
Example 10
Project: upvote   Author: google   File: utils_test.py    License: Apache License 2.0 6 votes vote down vote up
def testSameSchema_RepeatedProperty(self):

    # Initial schema
    class A(ndb.Model):
      a = ndb.StringProperty()
      b = ndb.StringProperty(repeated=True)

    # Create an entity using the initial schema
    inst = A(a='abc', b=['def'])
    inst.put()

    self.assertIsNotNone(inst.b)

    # Delete the property and save the entity
    datastore_utils.DeleteProperty(inst, 'b')
    inst.put()
    inst = A.get_by_id(inst.key.id())

    # The old data is...kinda gone :|
    self.assertEqual([], inst.b) 
Example 11
Project: upvote   Author: google   File: utils_test.py    License: Apache License 2.0 6 votes vote down vote up
def testDeleteValue(self):

    # Initial schema
    class A(ndb.Model):
      a = ndb.StringProperty()
      b = ndb.StringProperty()

    # Create an entity using the initial schema
    inst = A(a='abc', b='def')
    inst.put()

    self.assertIsNotNone(inst.b)

    # Delete the property and save the entity
    datastore_utils.DeletePropertyValue(inst, 'b')
    inst.put()
    inst = A.get_by_id(inst.key.id())

    # The old data is gone :)
    self.assertIsNone(inst.b) 
Example 12
Project: upvote   Author: google   File: utils_test.py    License: Apache License 2.0 6 votes vote down vote up
def testDatetimeAutoNowAdd(self):

    # Initial schema
    class A(ndb.Model):
      a = ndb.StringProperty()
      b = ndb.DateTimeProperty(auto_now_add=True)

    # Create an entity using the initial schema
    inst = A(a='abc')
    inst.put()

    # Delete the property and save the entity
    datastore_utils.DeletePropertyValue(inst, 'b')
    inst.put()

    self.assertTrue(datastore_utils.HasProperty(inst, 'b'))
    self.assertIsNotNone(inst.b) 
Example 13
Project: upvote   Author: google   File: utils_test.py    License: Apache License 2.0 6 votes vote down vote up
def testRepeatedProperty(self):

    # Initial schema
    class A(ndb.Model):
      a = ndb.StringProperty()
      b = ndb.StringProperty(repeated=True)

    # Create an entity using the initial schema
    inst = A(a='abc', b=['def'])
    inst.put()

    self.assertIsNotNone(inst.b)

    # Delete the property and save the entity
    datastore_utils.DeletePropertyValue(inst, 'b')
    inst.put()
    inst = A.get_by_id(inst.key.id())

    # The old data is gone
    self.assertEqual([], inst.b) 
Example 14
Project: upvote   Author: google   File: utils_test.py    License: Apache License 2.0 6 votes vote down vote up
def testRequiredField(self):

    # Initial schema but this time with a required property
    class A(ndb.Model):
      a = ndb.StringProperty()
      b = ndb.StringProperty(required=True)

    # Create an entity using the initial schema
    inst = A(a='abc', b='def')
    inst.put()

    # Delete the property and save the entity
    datastore_utils.DeletePropertyValue(inst, 'b')
    # Property required but no longer has a value.
    with self.assertRaises(Exception):
      inst.put() 
Example 15
Project: upvote   Author: google   File: utils_test.py    License: 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 16
Project: upvote   Author: google   File: handler_utils_test.py    License: Apache License 2.0 6 votes vote down vote up
def testQueryModel_TranslatePropertyQuery(self):
    class Foo(ndb.Model):
      foo = ndb.StringProperty()

      @classmethod
      def TranslatePropertyQuery(cls, field, term):
        return 'foo', 'bar'

    class FooQueryHandler(handler_utils.UserFacingQueryHandler):
      MODEL_CLASS = Foo

    # Request a nonsense query to be ignored by TranslatePropertyQuery.
    with self.LoggedInUser():
      q = FooQueryHandler()._QueryModel({'bar': 'baz'})
    # Create an entity satisfying the translated query.
    Foo(foo='bar').put()
    # Ensure the translated query finds the created entity.
    self.assertIsNotNone(q.get()) 
Example 17
Project: loaner   Author: google   File: bigquery_test.py    License: Apache License 2.0 5 votes vote down vote up
def test_generate_entity_schema(self):

    class NestedTestModel(ndb.Model):
      nested_string_attribute = ndb.StringProperty()

    class TestModel(ndb.Model):
      string_attribute = ndb.StringProperty()
      integer_attribute = ndb.IntegerProperty()
      boolean_attribute = ndb.BooleanProperty()
      nested_attribute = ndb.StructuredProperty(NestedTestModel)

    schema = bigquery._generate_entity_schema(TestModel())
    expected_schema_names = _populate_schema_names(self.entity_schema)
    schema_names = _populate_schema_names(schema)
    self.assertCountEqual(expected_schema_names, schema_names) 
Example 18
Project: jbox   Author: jpush   File: ndb.py    License: MIT License 5 votes vote down vote up
def get_TextField(kwargs):
    """
    Returns a ``TextField``, applying the ``ndb.StringProperty`` length limit
    of 500 bytes.
    """
    kwargs['validators'].append(validators.length(max=500))
    return f.TextField(**kwargs) 
Example 19
Project: jbox   Author: jpush   File: ndb.py    License: MIT License 5 votes vote down vote up
def convert_StringProperty(self, model, prop, kwargs):
        """Returns a form field for a ``ndb.StringProperty``."""
        if prop._repeated:
            return StringListPropertyField(**kwargs)
        kwargs['validators'].append(validators.length(max=500))
        return get_TextField(kwargs) 
Example 20
Project: locality-sensitive-hashing   Author: singhj   File: db_datastore.py    License: MIT License 5 votes vote down vote up
def __call__(cls, *args, **kwds):
        if kwds:
            #logging.info('Table called cls = %s, kwds = %s', cls, kwds)
            pass
        if cls not in cls._instances:
            cls._instances[cls] = super(Table, cls).__call__(*args, **{})
            datastore_type = {
                'text': ndb.StringProperty(),
                'list<bigint>': ndb.IntegerProperty(repeated = True),
                'list<int>': ndb.IntegerProperty(repeated = True),
                'int': ndb.IntegerProperty(),
                'ascii': ndb.StringProperty(indexed = False),
            }
            attr_list = kwds['attrs']
            attrs = {}
            for attr in attr_list:
                (name, typ) = tuple(attr.split())
                attrs[name] = copy.copy(datastore_type[typ])
            StorageProxy = type(cls.__name__, (ndb.Model,), attrs)

            setattr(cls._instances[cls], 'StorageProxy', StorageProxy)
            setattr(cls._instances[cls], 'attrs', kwds['attrs'])
            setattr(cls._instances[cls], 'p_keys', kwds['p_keys'])

            gql = "SELECT * FROM {name} WHERE {cond}"\
                .format(name = cls.__name__, cond = ' AND '.join([kwds['p_keys'][c]+'=:%d'%(c+1) for c in xrange(len(kwds['p_keys']))]))
            select = ndb.gql(gql)
            setattr(cls._instances[cls], 'select', select)

            parent_keys = kwds['p_keys'][1:]
            if parent_keys:
                gql = "SELECT * FROM {name} WHERE {cond}"\
                    .format(name = cls.__name__, cond = ' AND '.join([parent_keys[c]+'=:%d'%(c+1) for c in xrange(len(parent_keys))]))
                select_all_with_parent = ndb.gql(gql)
                setattr(cls._instances[cls], 'select_all_with_parent', select_all_with_parent)

        return cls._instances[cls] 
Example 21
Project: RSSNewsGAE   Author: liantian-cn   File: ndb.py    License: Apache License 2.0 5 votes vote down vote up
def get_TextField(kwargs):
    """
    Returns a ``TextField``, applying the ``ndb.StringProperty`` length limit
    of 500 bytes.
    """
    kwargs['validators'].append(validators.length(max=500))
    return f.TextField(**kwargs) 
Example 22
Project: RSSNewsGAE   Author: liantian-cn   File: ndb.py    License: Apache License 2.0 5 votes vote down vote up
def convert_StringProperty(self, model, prop, kwargs):
        """Returns a form field for a ``ndb.StringProperty``."""
        if prop._repeated:
            return StringListPropertyField(**kwargs)
        kwargs['validators'].append(validators.length(max=500))
        return get_TextField(kwargs) 
Example 23
Project: graphene-gae   Author: graphql-python   File: test_converter.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testNoneResult_raisesException(self, patch_convert):
        from graphene_gae.ndb.converter import convert_ndb_property
        patch_convert.get.return_value = lambda *_: None
        with self.assertRaises(Exception) as context:
            prop = ndb.StringProperty()
            prop._code_name = "my_prop"
            convert_ndb_property(prop)

        expected_message = 'Failed to convert NDB propeerty to a GraphQL field my_prop (StringProperty())'
        self.assertTrue(expected_message in context.exception.message, msg=context.exception.message) 
Example 24
Project: graphene-gae   Author: graphql-python   File: test_converter.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testStringProperty_shouldConvertToString(self):
        self.__assert_conversion(ndb.StringProperty, graphene.String) 
Example 25
Project: graphene-gae   Author: graphql-python   File: test_converter.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testStringProperty_repeated_shouldConvertToList(self):
        ndb_prop = ndb.StringProperty(repeated=True)
        result = convert_ndb_property(ndb_prop)
        graphene_type = result.field._type

        self.assertIsInstance(graphene_type, graphene.List)
        self.assertEqual(graphene_type.of_type, graphene.String) 
Example 26
Project: graphene-gae   Author: graphql-python   File: test_converter.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testStringProperty_required_shouldConvertToList(self):
        ndb_prop = ndb.StringProperty(required=True)
        result = convert_ndb_property(ndb_prop)
        graphene_type = result.field._type

        self.assertIsInstance(graphene_type, graphene.NonNull)
        self.assertEqual(graphene_type.of_type, graphene.String) 
Example 27
Project: graphene-gae   Author: graphql-python   File: test_converter.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testKeyProperty_withSuffix(self):
        my_registry = Registry()

        class User(ndb.Model):
            name = ndb.StringProperty()

        class UserType(NdbObjectType):
            class Meta:
                model = User
                registry = my_registry

        prop = ndb.KeyProperty(kind='User')
        prop._code_name = 'user_key'

        conversion = convert_ndb_property(prop, my_registry)

        self.assertLength(conversion, 2)

        self.assertEqual(conversion[0].name, 'user_id')
        self.assertIsInstance(conversion[0].field, DynamicNdbKeyStringField)
        _type = conversion[0].field.get_type()
        self.assertIsInstance(_type, NdbKeyStringField)
        self.assertEqual(_type._type, String)

        self.assertEqual(conversion[1].name, 'user')
        self.assertIsInstance(conversion[1].field, DynamicNdbKeyReferenceField)
        _type = conversion[1].field.get_type()
        self.assertIsInstance(_type, NdbKeyReferenceField)
        self.assertEqual(_type._type, UserType) 
Example 28
Project: graphene-gae   Author: graphql-python   File: test_converter.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testKeyProperty_withSuffix_required(self):
        class User(ndb.Model):
            name = ndb.StringProperty()

        my_registry = Registry()

        class UserType(NdbObjectType):
            class Meta:
                model = User
                registry = my_registry

        prop = ndb.KeyProperty(kind='User', required=True)
        prop._code_name = 'user_key'

        conversion = convert_ndb_property(prop, my_registry)

        self.assertLength(conversion, 2)

        self.assertEqual(conversion[0].name, 'user_id')
        self.assertIsInstance(conversion[0].field, DynamicNdbKeyStringField)
        _type = conversion[0].field.get_type()
        self.assertIsInstance(_type, NdbKeyStringField)
        self.assertIsInstance(_type._type, NonNull)
        self.assertEqual(_type._type.of_type, String)

        self.assertEqual(conversion[1].name, 'user')
        self.assertIsInstance(conversion[1].field, DynamicNdbKeyReferenceField)
        _type = conversion[1].field.get_type()
        self.assertIsInstance(_type, NdbKeyReferenceField)
        self.assertIsInstance(_type._type, NonNull)
        self.assertEqual(_type._type.of_type, UserType) 
Example 29
Project: graphene-gae   Author: graphql-python   File: test_converter.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testKeyProperty_withoutSuffix(self):
        my_registry = Registry()

        class User(ndb.Model):
            name = ndb.StringProperty()

        class UserType(NdbObjectType):
            class Meta:
                model = User
                registry = my_registry

        prop = ndb.KeyProperty(kind='User')
        prop._code_name = 'user'

        conversion = convert_ndb_property(prop, my_registry)

        self.assertLength(conversion, 2)

        self.assertEqual(conversion[0].name, 'user_id')
        self.assertIsInstance(conversion[0].field, DynamicNdbKeyStringField)
        _type = conversion[0].field.get_type()
        self.assertIsInstance(_type, NdbKeyStringField)
        self.assertEqual(_type._type, String)

        self.assertEqual(conversion[1].name, 'user')
        self.assertIsInstance(conversion[1].field, DynamicNdbKeyReferenceField)
        _type = conversion[1].field.get_type()
        self.assertIsInstance(_type, NdbKeyReferenceField)
        self.assertEqual(_type._type, UserType) 
Example 30
Project: googleapps-message-recall   Author: google   File: domain_user.py    License: Apache License 2.0 5 votes vote down vote up
def SetMessageState(cls, user_key_id, new_state):
    """Describe progress finding/purging a message for one user.

    Args:
      user_key_id: String (serializable) unique id of the user.
      new_state: String update for the ndb StringProperty field.
    """
    user = cls._GetUserByKey(user_key_id)
    if user:
      user.message_state = new_state
      user.put()