-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add fork of ndb's JsonProperty that works in the datastore web console
- Loading branch information
Showing
1 changed file
with
24 additions
and
1 deletion.
There are no files selected for viewing
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
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) |