如何通过实时侦听器python

时间:2020-05-28 16:44:51

标签: python google-cloud-firestore

很抱歉,如果其中的某些步骤没有意义,我正在努力完全理解实时侦听器。

我正在尝试将实时侦听器添加到应用程序的聊天部分,以便在新消息进入数据库时​​向屏幕添加新消息。在下面的代码中,当用户打开页面时,我将所有当前消息加载到屏幕上,然后我(尝试)添加实时侦听器,以便可以将任何新消息添加到屏幕上。

但是,doc_snapshot只是文档ID的列表,而不是我上面一直使用的message_dict,我如何访问doc_snapshot中每个文档的数据,而不只是ID?

还是我做的是完全错误的,打开屏幕时是否应该一次性加载消息,而不是使用实时侦听器加载消息并收听新消息?

self.local_id是已登录用户的ID,doc_id是正在发送消息的人员的ID。

    def move_to_chat(self, doc_id):
        group_id = self.local_id + ":"+ doc_id
        doc_ref = self.my_firestore.db.collection(u'messages').document(group_id)
        doc = doc_ref.get()
        if doc.exists: # Check if the document exists. If it does, load the messages to the screen
            get_messages = self.my_firestore.db.collection(u'messages').document(group_id).collection(group_id).order_by(u'Timestamp').limit(20)
            messages = get_messages.stream()
            for message in messages:
                message_dict = message.to_dict()
                try:
                    if message_dict['IdFrom'] == self.local_id:
                        #Add label to left of screen
                    else:
                        #Add label to right of screen
                except:
                    pass
        else: # If it doesn't, create it
            self.my_firestore.db.collection(u'messages').document(group_id).set({
                u'GroupId': group_id
            })
            add_to_doc = self.my_firestore.db.collection(u'messages').document(group_id).collection(group_id).document()
            add_to_doc.set({
                u'Timestamp': datetime.datetime.now()
            })

        # Watch for new messages
        self.query_watch = self.my_firestore.db.collection(u'messages').document(group_id).collection(group_id)
        # Watch the document
        self.query_watch.on_snapshot(self.on_snapshot)

    def on_snapshot(self, doc_snapshot, changes, read_time):
        for doc in doc_snapshot:
            #Here's where I'd like to access data from the documents, to find the message that has been added.

1 个答案:

答案 0 :(得分:0)

用于快照的Google Firestore documentation方法解释了表示Google Cloud Firestore API文档的类。您可以参考此文档以使返回值一致。