Esempio n. 1
0
    def __init__(self, parent=None, **kwargs):
        """
        Create a new instance of the model.

        Underneath, this creates the :class:`gcloud.datastore.Entity` and a :class:`gcloud.datastore.Key` for that
        entity.

        :param Key parent: A :class:`gcloud.datastore.key.Key` to use as a parent.
        :param kwargs: The value of the properties for this model. Unrecognised properties are ignored.
        :raises TypeError: if the id proper is the wrong type.
        """
        # Figure out the id value
        id_prop = self._properties[self._id_prop]
        id_value = kwargs.get(self._id_prop, None) or \
            (id_prop._default() if callable(id_prop._default) else id_prop._default)
        if not id_value:
            raise ValueError('You need to specify a value for your key_id property or use a default value.')

        # Create the key now we know our id
        id_value = id_prop.to_base_type(id_prop.validate(id_value))  # Make sure id is in the right form for storage
        if isinstance(parent, key.Key):
            self._key = key.Key(self.__class__.__name__, id_value, parent=parent)
        else:
            self._key = key.Key(self.__class__.__name__, id_value)
        super(Model, self).__init__(self._key, exclude_from_indexes=self._model_exclude_from_indexes)

        # Set our properties
        for attr in self._properties:
            setattr(self, attr, getattr(self, attr))

        for name in self._properties:  # Don't store random properties
            if name == self._id_prop:  # We already have the value of the id
                setattr(self, name, id_value)
            elif name in kwargs:
                setattr(self, name, kwargs[name])
Esempio n. 2
0
    def testModel(self):
        p = key.Key('ParentModel', 'foo')

        # key auto id (name)
        m = model.Model()
        self.assertEqual(m.key.id_or_name, m.id)
        self.assertEqual(m.key.kind, model.Model.__name__)
        # + parent
        m = model.Model(parent=p)
        self.assertEqual(m.key.path,
                         key.Key('ParentModel', 'foo', 'Model', m.id).path)

        # name from field with default
        class TestModel(model.Model):
            id = properties.TextProperty(default="abc", key_id=True)

        m = TestModel()
        self.assertEqual(m.key.id_or_name, "abc")
        self.assertEqual(m.id, "abc")
        # pass name
        m = TestModel(id='cba')
        self.assertEqual(m.key.id_or_name, "cba")
        self.assertEqual(m.id, "cba")
        # + parent
        m = TestModel(parent=p)
        self.assertEqual(m.key.path,
                         key.Key('ParentModel', 'foo', 'TestModel', m.id).path)
        # pass + parent
        m = TestModel(id='cba', parent=p)
        self.assertEqual(
            m.key.path,
            key.Key('ParentModel', 'foo', 'TestModel', 'cba').path)

        # name from field with callable default
        class TestModel(model.Model):
            id = model.TextProperty(default=lambda: "abc", key_id=True)

        m = TestModel()
        self.assertEqual(m.key.id_or_name, "abc")
        self.assertEqual(m.id, "abc")

        # name from int field with callable default
        class TestModel(model.Model):
            id = model.IntegerProperty(default=lambda: 111, key_id=True)

        m = TestModel()
        self.assertEqual(m.key.id_or_name, 111)
        self.assertEqual(m.id, 111)

        # name from IdProeprty
        class TestModel(model.Model):
            the_id = model.IdProperty(key_id=True)
Esempio n. 3
0
    def filter(cls, ids):
        """
        Get the entities identified by ids.

        :param list ids: The ids to fetch.
        :return: a list of Model instances
        """
        entities = api.get([key.Key(cls.__name__, i) for i in ids])
        return [cls.from_entity(e) for e in entities if e]
Esempio n. 4
0
    def get_by_id(cls, id):
        """
        Get the entity identified by id.

        :param id: The id of the entity to fetch
        :return: The model instance.
        """
        e = api.get([key.Key(cls.__name__, id)])
        if e:
            return cls.from_entity(e[0])
        raise ObjectDoesNotExist
# This was run against version 0.3.0.

import datetime
import time

from gcloud import datastore
from gcloud.datastore import datastore_v1_pb2 as datastore_pb
from gcloud.datastore import helpers
from gcloud.datastore import key

PRIVATE_KEY_PATH = 'Foo'
CLIENT_EMAIL = 'Bar'
DATASET_ID = 'Baz'
DATASET = datastore.get_dataset(DATASET_ID, CLIENT_EMAIL, PRIVATE_KEY_PATH)
CONNECTION = DATASET.connection()
PARTIAL_KEY_PB = key.Key(path=[{'kind': 'Foo'}]).to_protobuf()

BASE_DATA = {
    'now': datetime.datetime.utcnow(),
    'nickname': 'Jeff',
    'email': '*****@*****.**',
    'user_id': '123456789012345678901',
}

FANCY_DATASET_ID = 's~' + DATASET_ID


def check_key_pb(key_pb):
    if (key_pb.partition_id.dataset_id != FANCY_DATASET_ID
            or len(key_pb.path_element) != 1
            or key_pb.path_element[0].kind != u'Foo'):