将GqlQuery结果集转换为python字典
-
03-07-2019 - |
题
假设我有一个这样的模型
class Foo(db.Model):
id = db.StringProperty()
bar = db.StringProperty()
baz = db.StringProperty()
我要去像这样的GqlQuery
foos = db.GqlQuery("SELECT * FROM Foo")
我想获取GqlQuery的结果并转换为某种JSON字符串,我可以使用不同的语言进行操作。
以下是我现在正在做的事情
-
将一个方法添加到 Foo 类,将其转换为字典
def toDict(self): return { 'id': self.id, 'bar': self.bar, 'baz': self'baz }
-
循环遍历GqlQuery结果并手动将每个Foo实例添加到字典
fooDict = {} for foo in foos: fooDict[foo.id] = foo.toDict() return simplejson.dumps(fooDict)
醇>
我的上述方法有效,但感觉有点粗糙。
是否有更清洁,更“Pythonic”的产品?处理这个的方法?
结束格式不一定是我上面所做的。它只需要很好地转换为JSON,所以我可以从Javascript / PHP /中处理它。
解决方案
查看 google .appengine.api.datastore 。它是google.appengine.ext.db构建的较低级别数据存储区API,它返回实体对象,它们是子类dict。你可以使用GQL查询它 google.appengine.ext.gql 或(我的个人偏好)使用Query类,这样就无需为GQL解析器构造文本字符串来解析。 api.datastore中的Query类的行为与此处记录的完全相同(但返回较低级别的Entity对象而不是Model实例)。
例如,上面的查询可以重新表述为“datastore.Query(" Foo”)。all()"。
其他提示
我不能做得太好,但这里有几个想法:
class Foo:
id = db.StringProperty() # etc.
json_attrs = 'id bar baz'.split()
# Depending on how easy it is to identify string properties, there
# might also be a way to assign json_attrs programmatically after the
# definition of Foo, like this
Foo.json_attrs = [attr for attr in dir(Foo)
if isStringProperty(getattr(Foo, attr))]
fooDict=dict((foo.id,dict(getattr(foo, attr)
for attr in Foo.json_attrs))
for foo in foos)
http://code.google.com/p/google-app-engine-samples/source/browse/trunk/geochat/json.py?r=55
编码器方法可以很好地解决您的GQL到JSON需求。我建议摆脱一些过时的日期时间选项....作为一个时代的时间?真的?
您可以在GAE上使用web2py并执行:
db.define_table('foo',SQLField('bar'),SQLField('baz'))
rows=db(db.foo.id>0).select()
### rows is a list, rows.response is a list of tuples
for row in rows: print dict(row)
运行Oracle,Postgresql,Mssql,mysql等等。