如何解决“查询”对象在Python中没有属性“ to_dict”错误?

时间:2019-08-03 08:09:15

标签: python-3.x firebase google-cloud-firestore google-cloud-functions

我已经创建了一个云函数,用于在特定条件下从Firestore中获取数据。我已经成功从Firestore提取了数据,但是,从Firestore接收的数据在“查询对象”中。如何将该查询对象转换为字典类型?

我尝试使用.to_dict()函数对其进行转换,但是它给了我一个错误,

  

错误:函数崩溃。详细信息:“查询”对象没有属性   'to_dict'

我也尝试过这次访问: How to convert firestore query response to json using python,但是没有用。

insights = db.collection('GA_data').where('artist_id','==',request_json['artist_id'])
    insights = insights.to_dict() 
    print(insights)

这是我的request_json

{'artist_id': #some_number}

我的预期结果是

{
"artist_id" : #some_number,
"avgTimeOnPage" : "0.0",
"bouncerate" : "0.0",
"date" : "#some_date",
"newUsers"  : "0",
"pageviews" : "0",
"sessionDuration" : "0.0",
"slug" : "#some_slug",
"users" : "0" 
}

但是我的实际输出是:

Query object : 
google.cloud.firestore_v1.query.Query object at 0x2a5f28059438

然后,在.to_dict()函数之后:

  

错误:函数崩溃。详细信息:“查询”对象没有属性   'to_dict'

2 个答案:

答案 0 :(得分:1)

您必须将stream()附加到query上,然后使用for循环从查询可能返回的每个文档中获取数据,在您的情况下,我猜只有一个。您的查询可能包含多个文档。 然后您的代码可能是这样的:

insights = db.collection('GA_data').where('artist_id', '==', request_json['artist_id']
for document in insights.stream():
    print(document.to_dict())

答案 1 :(得分:0)

用于Firestore Query类的Firebase Admin SDK Python API不包含to_dict()方法。

您可以使用以下示例中的on_snapshot(callback)方法,然后在文档上调用to_dict()

from google.cloud import firestore_v1

db = firestore_v1.Client()
query_ref = db.collection('GA_data').where('artist_id','==',request_json['artist_id'])

def on_snapshot(docs, changes, read_time):
    for doc in docs:
        print(u'{} => {}'.format(doc.id, doc.to_dict()))

# Watch this query
query_watch = query_ref.on_snapshot(on_snapshot)

# Terminate this watch
query_watch.unsubscribe()