You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository was archived by the owner on Apr 19, 2022. It is now read-only.
I think most "legacy" GAE users will find this useful:
"""Base models and utilities used by the derived ones."""importdatetimeimportloggingimportndb_ormasndbfromgoogle.cloudimportdatastorefrom<project>importapp, settings# Datastore default client settings.PROJECT=settings.PROJECT_IDNAMESPACE=app.config["DATASTORE_NAMESPACE"]
NDB_KWARGS= {"project": PROJECT, "namespace": NAMESPACE}
# Module level singleton client used in all DB interactions. This is lazy inited when# is used only, so we don't have any issues with Datastore agnostic tests/debugging,# because creating a client will require valid credentials.client=NoneclassBaseModel(ndb.Model):
"""Common model properties and functionality."""# String used for properties with no available data.NOT_SET="N/A"created_at=ndb.DateTimeProperty(auto_now_add=True)
def__init__(self, *args, **kwargs):
self._get_client() # Activates all NDB ORM required features.kwargs.update(NDB_KWARGS)
super().__init__(*args, **kwargs)
@classmethoddefmodel_name(cls):
returncls.__name__.replace("Model", "")
@classmethoddefnormalize(cls, value):
ifvalueisNone:
returncls.NOT_SETreturnvalue@staticmethoddef_get_client():
globalclientifnotclient:
client=datastore.Client(**NDB_KWARGS)
ndb.enable_use_with_gcd(client=client, **NDB_KWARGS)
returnclient@classmethoddefquery(cls, **kwargs):
query=cls._get_client().query(kind=cls._get_kind(), **kwargs)
returnquery@classmethoddefall(cls, query=None, keys_only=False, **kwargs):
query=queryorcls.query()
query.order= ["-created_at"]
ifkeys_only:
query.keys_only()
returnlist(query.fetch(**kwargs))
@propertydefmyself(self):
"""Return the current DB version of the same object."""returnself.key.get()
@propertydefexists(self):
"""Checks if the entity is saved into the Datastore."""try:
returnbool(self.myself) ifself.keyandself.key.idelseFalseexceptException:
returnFalsedefput(self):
"""Saving the entity into the Datastore."""self._get_client().put(self)
returnself.key@classmethoddefput_multi(cls, entities):
"""Multiple save in the DB without interfering with `cls.put` function."""cls._get_client().put_multi(entities)
return [entity.keyforentityinentities]
defremove(self):
"""Removes current entity and its dependencies (if any)."""self.key.delete()
@classmethoddefremove_multi(cls, keys):
cls._get_client().delete_multi(keys)
@propertydefurlsafe(self):
returnself.key.to_legacy_urlsafe().decode(settings.ENCODING)
@classmethoddefget(cls, urlsafe_or_key):
ifisinstance(urlsafe_or_key, (str, bytes)):
key=ndb.Key(cls, **NDB_KWARGS)
complete_key=key.from_legacy_urlsafe(urlsafe_or_key)
else:
complete_key=urlsafe_or_keyitem=complete_key.get()
ifnotitem:
raiseException("item doesn't exist")
returnitem
I think most "legacy" GAE users will find this useful:
Don't be sceptical, this is tested by these:
Just replace
<project>with your package name (under a Flask app for example).