Created
August 27, 2012 18:27
-
-
Save gregorynicholas/3491119 to your computer and use it in GitHub Desktop.
A property to store serialized protorpc message models as Json data objectsin the appengine datastore, avoiding weird string key accessors from using aJsonProperty, and extra datastore hits using a StructuredProperty.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'''A property to store serialized protorpc message models as Json data objects | |
in the appengine datastore, avoiding weird string key accessors from using a | |
JsonProperty, and extra datastore hits using a StructuredProperty.''' | |
from libs import ndb | |
from libs.protorpc.remote import protojson | |
class JsonMessageProperty(ndb.JsonProperty): | |
_message_type = None | |
# _attributes = ['_name', '_indexed', '_repeated', '_required', '_default', | |
# '_choices', '_validator', '_verbose_name', '_message_type'] | |
def __init__(self, message_type=None, *args, **kwds): | |
self._attributes.append('_message_type') | |
self._message_type = message_type | |
ndb.JsonProperty.__init__(self, *args, **kwds) | |
def _default(self): | |
return message_type() | |
def _to_base_type(self, value): | |
# decode message to json, store value in datastore | |
return self.encode_message_to_json(value) | |
def encode_message_to_json(self, value): | |
return protojson.encode_message(value) | |
def _from_base_type(self, value): | |
# read from datastore, encode value to message object | |
return self.encode_json_to_message(self._message_type, value) | |
def encode_json_to_message(self, message_type, value): | |
return protojson.decode_message(message_type, value) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from google.appengine.ext import ndb | |
from jsonproperty import JsonMessageProperty | |
from protorpc import messages | |
class ModelMeta(messages.Message): | |
created = messages.FloatField(1) | |
edited = messages.FloatField(2) | |
something_else = messages.StringField(3) | |
class SomeModel(ndb.Model): | |
meta = JsonMessageProperty(message_type=ModelMeta) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment