I'm building an app with Google Cloud services, the application is deployed through Google App Engine.
I would like to show information in real-time with Flask through Firestore's onSnapshot() method, so i tried to use flask_socketio to send the information to the client, but it doesn't work inside on_snapshot.
from flask import Flask, render_template, request
from google.cloud import firestore
from flask_socketio import SocketIO, emit
db = firestore.Client()
app = Flask(__name__)
socketio = SocketIO(app)
@app.route("/", methods=["GET"])
def map():
live_ref = db.collection("events").document("live_events").get()
return render_template("index.html", rec=live_ref.to_dict()["displayed_events"])
@socketio.on("test", namespace="/")
def test():
def on_snapshot(doc_snapshot, changes, read_time):
for doc in doc_snapshot:
print(f"Received document snapshot: {doc.to_dict()}")
with app.app_context():
emit("message", "test_message", namespace="/", broadcast=True)
test_ref = db.collection("events").document("live_events")
test_watch = test_ref.on_snapshot(on_snapshot)
if __name__ == "__main__":
socketio.run(app, debug=True)
index.html
$(document).ready(function() {
var socket = io.connect('http://127.0.0.1:5000');
socket.on('connect', function() {
socket.emit('test');
});
socket.on("message", function(msg) {
$("#messages").append('<li>'+msg+'</li>');
});
});
</script>
<ul id="messages"></ul>
So i was wondering how the problem could be solved or what other methods/services could be used to be able to receive data changes in real-time from the db firestore and display them on the client side. I have seen that it is possible to use on_snapshot directly from the client, but i would like to avoid using the firebase console.