Last active
September 5, 2018 18:59
-
-
Save bengrunfeld/062d0d8360667c47bc5b to your computer and use it in GitHub Desktop.
Convert NDB result to JSON Serializable data
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
def make_ndb_return_data_json_serializable(data): | |
"""Build a new dict so that the data can be JSON serializable""" | |
result = data.to_dict() | |
record = {} | |
# Populate the new dict with JSON serializiable values | |
for key in result.iterkeys(): | |
if isinstance(result[key], datetime.datetime): | |
record[key] = result[key].isoformat() | |
continue | |
record[key] = result[key] | |
# Add the key so that we have a reference to the record | |
record['key'] = data.key.id() | |
return record | |
def filter_results(qry): | |
""" | |
Send NDB query result to serialize function if single result, | |
else loop through the query result and serialize records one by one | |
""" | |
result = [] | |
# check if qry is a list (multiple records) or not (single record) | |
if type(qry) != list: | |
record = make_ndb_return_data_json_serializable(qry) | |
return record | |
for q in qry: | |
result.append(make_ndb_return_data_json_serializable(q)) | |
return result | |
# Usage: | |
# | |
# qry = TodoModel.query().fetch() | |
# serialized_results = filter_results(qry) | |
# | |
# self.response.headers['Content-Type'] = 'text/plain' | |
# self.response.write(json.dumps(serializable_results)) | |
# | |
# | |
# Example: | |
# | |
# For a working implemented example of this, see: | |
# https://github.com/bengrunfeld/gae-restful-api/blob/master/handlers.py |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks! Work excellent!!! Thank you very much!