我正试图让Flask监听Firestore树中的实时更新。
我在link的文档中找到了以下代码段:
# Create a callback on_snapshot function to capture changes
def on_snapshot(doc_snapshot, changes, read_time):
for doc in doc_snapshot:
print(u'Received document snapshot: {}'.format(doc.id))
doc_ref = db.collection(u'cities').document(u'SF')
# Watch the document
doc_watch = doc_ref.on_snapshot(on_snapshot)
但是我不确定如何在Flask中使用它。
基本上,我想要让Flask监听Firestore中文档中的更改,然后将这些更改发送到我的前端应用程序(Reactjs)。我一直在看Flask-SocketIO,这似乎是我所需要的,但我不确定。
有人可以帮我吗?
修改
我正在尝试这样做:
# Create a callback on_snapshot function to capture changes
def on_snapshot(doc_snapshot, changes, read_time):
for doc in doc_snapshot:
flask_print("Received document snapshot: {}".format(doc.id))
flask_print("snapshot was recieved from firebase!")
emit("snapshot", {"data": doc.id})
@socketio.on("snapshot")
def snapshot_to_ferontend(snapshot):
flask_print("snapshot was sent to frontend!")
send(snapshot)
class SubscribeToGameById(Resource):
def __init__(self):
parser = reqparse.RequestParser()
parser.add_argument("game_id", required=True)
self.args = parser.parse_args()
def put(self):
doc_ref = db.collection("games").document(self.args["game_id"])
doc_ref.on_snapshot(on_snapshot)
但是我收到一条错误消息:“ RuntimeError:在请求上下文之外工作。”
答案 0 :(得分:0)
您可以使用库flask-boiler
来提供内容。像这样在视图模型中介器notify
中实现GameViewMediator
方法:
class GameViewMediator(ViewMediatorDAV):
def notify(obj):
send(obj.to_dict())
并将您的视图模型GameView
绑定到域模型Game
:
game_view = GameView()
game_view.bind_to(key="game", obj_type=Game, doc_id="game_id")
game_view.register_listener()
您应该看到websocket发出每一次更改的游戏快照。