【问题标题】:Firebase RTDB Listener doesn't work with FastAPIFirebase RTDB 侦听器不适用于 FastAPI
【发布时间】:2021-07-13 16:31:47
【问题描述】:

这是我与 Firebase RTDB 侦听器相关的代码:

import firebase_admin
from firebase_admin import credentials
from firebase_admin import db


class FirebaseConfig:
    reference = None
    listenerRegistration = None

    def __init__(self):
        cred = credentials.Certificate("path_to_credentials.json")
        firebase_admin.initialize_app(
            cred,
            {'databaseURL': 'database_url'}
        )
        self.reference = db.reference("Users")
        self.listenerRegistration = self.reference.listen(self.userListener)

    def userListener(self, event):
        print("Listener Started.")
        try:
            print(event.data)
            updateData() # A function to update our local database
        except Exception as e:
            raise Exception("Listener Error" + str(e))

    def stopListening(self):
        print("Closing Listener")
        self.listenerRegistration.close()

我现在面临的问题是这个监听器不起作用。打印语句不打印任何内容。我认为这是因为 FastAPI。有什么办法可以让它工作吗?

如果它们不能很好地协同工作,您是否有任何替代解决方案?

【问题讨论】:

  • 你在哪里调用这些方法?我们能看到调用代码吗?
  • 和FastAPI有什么关系?没有 FastAPI 是否可以工作?你如何配置这个?
  • @fchancel,我可以分享代码。但是,这些函数的调用仅限于此。您可以看到我在类初始化本身中添加了侦听器。在开始我的 FastAPI 代码之前,我已经为该类创建了一个对象。
  • @MatsLindh 在我关闭 FastAPI 服务器后它实际上可以工作。这就是为什么我遇到所有这些麻烦。因此,在服务器关闭后,它会打印所有数据和内容。所以,我认为由于 FastAPI 存在一些问题。如果您有其他相同的选择,我会愿意接受。
  • 如何设置监听器并启动它们?您是否尝试过将 Firebase 部分移到自己的线程中?该问题可能与 uvicorn 使用自己的事件循环有关,因此它不与 firebase 的事件循环合作。有关 uvicorn 的可能解决方案,请参阅stackoverflow.com/questions/66275747/…;如果 firebase_admin 有类似的可能,请检查文档。

标签: python firebase-realtime-database fastapi


【解决方案1】:

我想这可能是因为我的 uvicorn 服务器使用了 80 端口。我改变了它并且它起作用了。 这是最可能的原因。不能肯定。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-16
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多