Search code examples
pythonmongodbmeteorreal-timeddp

See real time changes in data using python meteor


I am using Python to retrieve data from Mongo database to analyze it. So I am changing data using meteor app and client python to retrieve it in a real time. This is my code:

from MeteorClient import MeteorClient
def call_back_meth():
    print("subscribed")
client = MeteorClient('ws://localhost:3000/websocket')
client.connect()
client.subscribe('tasks', [], call_back_meth)
a=client.find('tasks')
print(a)

when I run this script, it only show me current data in 'a' and console will close,

I want to let the console stay open and print data in case of change. I have used While True to let script running and see changes but I guess it's not a good solution. Is there any another optimized solution?


Solution

  • To get realtime feedback you need to subscribe to changes,and then monitor those changes. Here is an example of watching tasks:

    from MeteorClient import MeteorClient
    
    def call_back_added(collection, id, fields):
        print('* ADDED {} {}'.format(collection, id))
        for key, value in fields.items():
            print('  - FIELD {} {}'.format(key, value))
    
        # query the data each time something has been added to
        # a collection to see the data `grow`
        all_lists = client.find('lists', selector={})
        print('Lists: {}'.format(all_lists))
        print('Num lists: {}'.format(len(all_lists)))
    
    client = MeteorClient('ws://localhost:3000/websocket')
    client.on('added', call_back_added)
    client.connect()
    client.subscribe('tasks')
    
    # (sort of) hacky way to keep the client alive
    # ctrl + c to kill the script
    while True:
        try:
            time.sleep(1)
        except KeyboardInterrupt:
            break
    
    client.unsubscribe('tasks')
    

    (Reference) (Docs)