Data Namespaces with Google Cloud Datastore

Sun, 30 October 2016

test_model.py
from google.appengine.ext import ndb
from lib.model.abstract.abstract_model import AbstractModel


class TestModel(AbstractModel):

    modifiedDate = ndb.DateTimeProperty(indexed=False, auto_now=True, name='md')  # type: datetime.datetime
    name = ndb.StringProperty(indexed=True)

    def as_public(self):
        """
        :rtype: dict
        """
        return {
            u"id": self.get_id(),
            u"name": self.name
        }
abstract_model.py
from google.appengine.ext import ndb


class AbstractModel(ndb.Model):

    def get_id(self):
        """
        :rtype: int
        """
        return self.key.id()
create_data.py
from lib.model.test_model import TestModel

a = TestModel()
a.name = "default"
a.put()

a = TestModel(namespace="foo_one")
a.name = "one"
a.put()

a = TestModel(namespace="foo_two")
a.name = "two"
a.put()
get_data.py
from lib.model.test_model import TestModel

data = []
data.append(
    TestModel.query(TestModel.name == "default").fetch(1)[0].as_public()
)
data.append(
    TestModel.query(TestModel.name == "one", namespace="foo_one").fetch(1)[0].as_public()
)
data.append(
    TestModel.query(TestModel.name == "two", namespace="foo_two").fetch(1)[0].as_public()
)

# [
#   {
#     "id": 5629499534213120,
#     "name": "default"
#   },
#   {
#     "id": 5629499534213120,
#     "name": "one"
#   },
#   {
#     "id": 5629499534213120,
#     "name": "two"
#   }
# ]



# ... OR ...

data = []
data.append(
    TestModel.get_by_id(5629499534213120).as_public()
)
data.append(
    TestModel.get_by_id(5629499534213120, namespace="foo_one").as_public()
)
data.append(
    TestModel.get_by_id(5629499534213120, namespace="foo_two").as_public()
)

# [
#   {
#     "id": 5629499534213120,
#     "name": "default"
#   },
#   {
#     "id": 5629499534213120,
#     "name": "one"
#   },
#   {
#     "id": 5629499534213120,
#     "name": "two"
#   }
# ]



# ... OR ...

from google.appengine.ext import ndb
data = []
data.append(
    ndb.Key('TestModel', 5629499534213120).get().as_public()
)
data.append(
    ndb.Key('TestModel', 5629499534213120, namespace='foo_one').get().as_public()
)
data.append(
    ndb.Key('TestModel', 5629499534213120, namespace='foo_two').get().as_public()
)

# [
#   {
#     "id": 5629499534213120,
#     "name": "default"
#   },
#   {
#     "id": 5629499534213120,
#     "name": "one"
#   },
#   {
#     "id": 5629499534213120,
#     "name": "two"
#   }
# ]