json - 将 ndb.Model 序列化为 JSON 的 App 引擎数据存储 to_dict 替代方案

标签 json python-2.7 google-app-engine google-cloud-datastore app-engine-ndb

我有一个 ndb.Model 想要转换为 JSON。

class Users(ndb.Model):
    username = ndb.StringProperty(indexed=True)
    password= ndb.StringProperty(indexed=True)
    created_at = ndb.DateTimeProperty(auto_now_add=True)

user = Users.query(Users.username==username).get()
rv = json.dumps(user.to_dict()) 
print(rv)

它抛出这个错误:
 TypeError: datetime.datetime(2013, 11, 24, 3, 40, 15) is not JSON serializable

这里的大多数解决方案都是针对 db.Model 的,并且已经过时了。

SDK 版本 1.9.10

最佳答案

您可以扩展 Property 类来处理特殊情况。它适用于任何属性类型。

from google.appengine.ext import ndb

class DateTimeProperty(ndb.DateTimeProperty):
    # Override to allow JSON serialization
    def _get_for_dict(self, entity):
        value = super(DateTimeProperty, self)._get_for_dict(entity);
        return value.isoformat()

然后在您的模型中使用它:
class Users(ndb.Model):
    username = ndb.StringProperty(indexed=True)
    password= ndb.StringProperty(indexed=True)
    created_at = DateTimeProperty(auto_now_add=True)

to_dict()就像你通常会做的那样:
user = Users.query(Users.username==username).get()
user.to_dict()

关于json - 将 ndb.Model 序列化为 JSON 的 App 引擎数据存储 to_dict 替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25871308/

相关文章:

javascript - 从 JSON 字符串拆分有效负载

javascript - d3.js 更新饼图

python - 数据解析,Pythonic 方式

Python:以时间为优先级的优先级队列

google-app-engine - 云端点 HTTP Cookie

google-app-engine - GAE/J 中的数据库设计 : relational modelling vs entity-attribute-value

ios - 使用NSDictionary进行JSON解析并按键查找值

json - 如何添加utf8解码器解决flutter http请求乱码问题?

python - 如何从大型数据集中提取每天每小时的 500 个条目?

mysql - 使用 Cloud SQL 在 Google App Engine 上扬 sails 起航