Search code examples
pythonwebsocketpython-asynciotornadononblocking

How to handle coroutine when using tornado websockets


I'm using tornado websockets and it works fine.

However, I'd like to listen for changes to a MongoDB Collection and send new changes to the websocket client.

I cannot get it running with threads, and I saw that using threads with tornado is discouraged.

I'm really stuck right now. How can I proceed?

(blocking) Code right now:

    def open(self):
        print("Opening Connection")
        with self.collection.watch() as stream:
            for change in stream:
                doc = change["fullDocument"]
                self.write_message(u"%s" % json.dumps(doc))

Solution

  • It looks like Motor can handle Mongodb changestreams. https://motor.readthedocs.io/en/stable/api-asyncio/asyncio_motor_change_stream.html

    Personally, I find RethinkDB or Firebase are better alternatives for realtime features like this. But without knowing your needs, I cannot say if this is a good for you.