【问题标题】:python-firebase get items when addedpython-firebase 添加时获取项目
【发布时间】:2016-04-11 21:22:05
【问题描述】:

所以我目前正在使用python-firebase,并且我之前一直在使用 JavaScript 和 Firebase。在 JS 中有 ref.on('child_added'),但我希望对 python-firebase 做同样的事情(每次添加节点时我都必须检查 firebase,所以我假设我需要这样的东西)。

那么我该怎么做呢?

【问题讨论】:

    标签: python firebase firebase-realtime-database


    【解决方案1】:

    使用Firebase's REST API(这是他们的python API 的底层内容),您使用POST 请求保存元素,该请求返回添加元素的ID,因此将其保留在某个地方。检索您的元素并遍历它们以获取相关 ID:

    # assume your instance is called phones and your username is jack, change as appropriate
    def get_object(newest_id):
        objects = requests.get('https://samplechat.firebaseio-demo.com/users/jack/phones.json').json()
        added_object = [obj for obj in objects if obj == newest_id][0]
        return added_object
    
    def add_object(dictionary_representing_object):
        newest_id = requests.post('https://samplechat.firebaseio-demo.com/users/jack/phones.json', json=json.dumps(dictionary_representing_object), verify=False).json()['name']
        stored_object = get_object(newest_id) # stored_object will be a superset of what's in dictionary_representing_object -- it will have an additional entry representing firebase's unique id
    

    希望对您有所帮助。

    【讨论】:

    • 谢谢,但是我不必一遍又一遍地调用它,还是在添加某些项目后它会自动执行?这个想法是在添加记录后发送通知
    • 实际上,监听器是一个执行我所概述的服务器端进程。
    【解决方案2】:

    @hd1 的答案有效并使用您已经使用的 python-firebase 库。但正如你所说,它确实必须轮询更新。

    另一种方法是收听Firebase's REST streaming API。有一个Python example of how to consume the REST events(使用 Python 请求和 sseclient 库)。读取循环为here:

            self.sse = ClosableSSEClient(URL)
            for msg in self.sse:
                msg_data = json.loads(msg.data)
                if msg_data is None:    # keep-alives
                    continue
                path = msg_data['path']
                data = msg_data['data']
                if path == '/':
                    # initial update
                    if data:
                        keys = data.keys()
                        keys.sort()
                        for k in keys:
                            self.message_queue.put(data[k])
                else:
                    # must be a push ID
                    self.message_queue.put(data)
    

    虽然它不像您之前使用的原生 JavaScript 客户端那么简单,但它与 Python 中的功能非常接近。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      • 2019-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多