0

我正在尝试使用 Flask 和 Firestore 开发网络聊天。我设置了一个流程来接收来自 firestore 的新消息(当数据库发生变化时)并通过 websockets 发送到 UI。像这样的东西:

Python:

@sockets.route('/messages')
def chat_socket(ws):
  message = None
  def callback_snapshot(col_snapshot, changes, read_time):
    with app.app_context():
      Messages = []
      for change in changes:
        if change.type.name == 'ADDED':
          Messages.append(change.document)
      conversation = render_template(
          'conversation.html',
          Messages = Messages,
        )
      numberID = None
      if len(col_snapshot) > 0:
        for i in col_snapshot:
          a = i 
        numberID = a.reference.parent.parent.id

      response = json.dumps({
        'conversation': conversation,
        'numberID': numberID
        })
      ws.send(response)

  while not ws.closed:

    response = json.loads(ws.receive())
    newNumberID = response['newNumberID'].strip()

    query_snapshot = fn.GetMessages(newNumberID)
    doc_watch = query_snapshot.on_snapshot(callback_snapshot)

    if message is None:
      continue

Javascript:

    function messages(numberID) {
  var scheme = window.location.protocol == "https:" ? 'wss://' : 'ws://';
  var webSocketUri =  scheme
    + window.location.hostname
    + (location.port ? ':'+location.port: '')
    + '/messages';

/* Get elements from the page */
  var form = $('#chat-form');
  var textarea = $('#chat-text');
  var output = $('.messages');
  var status = $('.messages');

  var websocket = new WebSocket(webSocketUri);

  websocket.onopen = function() {};

  websocket.onclose = function() {};

  websocket.onmessage = function(e) {    
    numberID = JSON.parse(e.data).numberID
    conversation = JSON.parse(e.data).conversation
    output.append(conversation);   
    if (numberID == null){
      output.empty();
    }};

  websocket.onerror = function(e) {console.log(e);};
  websocket.onopen = () => websocket.send(numberID);

};

问题是:当我使用 col_snapshot 作为消息时,除了每次发送消息时我都会将整个 firestore 集合发送给用户之外,一切都很好。所以它完全没有效率。当我只为更改设置回调时,如上所述,如果我多次触发该函数,我以某种方式为同一个集合设置了多个侦听器,因此我在 UI 中获得了多个“更改更新”。我如何跟踪这些听众,以便每个集合只设置一个听众?

4

1 回答 1

0

正如您从文档中看到的那样,您应该只在每个文档中调用GetMessagesandon_snapshot一次。

@sockets.route('/messages')
def chat_socket(ws):
  message = None
  def callback_snapshot(col_snapshot, changes, read_time):
    with app.app_context():
      # Rest of the function ...
      ws.send(response)

  response = json.loads(ws.receive())
  numberID = response['newNumberID'].strip()
  query_snapshot = fn.GetMessages(numberID)
  doc_watch = query_snapshot.on_snapshot(callback_snapshot)
  while not ws.closed:
    newNumberID = response['newNumberID'].strip()
    response = json.loads(ws.receive())
    if newNumberID != numberID:
      numberID = newNumberID
      query_snapshot = fn.GetMessages(numberID)
      doc_watch = query_snapshot.on_snapshot(callback_snapshot)

于 2019-12-13T10:50:20.317 回答