Skip to content

Commit

Permalink
add fork of ndb's JsonProperty that works in the datastore web console
Browse files Browse the repository at this point in the history
  • Loading branch information
snarfed committed Feb 24, 2023
1 parent b9fcfec commit c5cf061
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion models.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,34 @@
"""App Engine datastore model base classes and utilites.
"""App Engine datastore model base classes, properties, and utilites.
"""
from google.cloud import ndb

from oauth_dropins.webutil.util import json_dumps, json_loads


class StringIdModel(ndb.Model):
"""An ndb model class that requires a string id."""
def put(self, *args, **kwargs):
"""Raises AssertionError if string id is not provided."""
assert self.key and self.key.string_id(), 'string id required but not provided'
return super(StringIdModel, self).put(*args, **kwargs)


class JsonProperty(ndb.TextProperty):
"""Fork of ndb's that subclasses TextProperty instead of BlobProperty.
This makes values show up as normal, human-readable, serialized JSON in the
web console.
https://github.com/googleapis/python-ndb/issues/874#issuecomment-1442753255
"""
def _validate(self, value):
if not isinstance(value, dict):
raise TypeError("JSON property must be a dict")

def _to_base_type(self, value):
as_str = json_dumps(value, separators=(",", ":"), ensure_ascii=True)
return as_str.encode("ascii")

def _from_base_type(self, value):
if not isinstance(value, str):
value = value.decode("ascii")
return json_loads(value)

0 comments on commit c5cf061

Please sign in to comment.