couchdb-python change notifications

一个人想着一个人 提交于 2019-12-03 12:57:02

I use long polling rather than continous, and that works ok for me. In long polling mode db.changes blocks until at least one change has happened, and then returns all the changes in a generator object.

Here is the code I use to handle changes. settings.db is my CouchDB Database object.

since = 1
while True:
    changes = settings.db.changes(since=since)
    since = changes["last_seq"]
    for changeset in changes["results"]:
        try:
           doc = settings.db[changeset["id"]]
        except couchdb.http.ResourceNotFound:
           continue
        else:
           // process doc

As you can see it's an infinite loop where we call changes on each iteration. The call to changes returns a dictionary with two elements, the sequence number of the most recent update and the objects that were modified. I then loop through each result loading the appropriate object and processing it.

For a continuous feed, instead of the while True: line use for changes in settings.db.changes(feed="continuous", since=since).

I setup a mailspooler using something similar to this. You'll need to also load couchdb.Session() I also use a filter for only receiving unsent emails to the spooler changes feed.

from couchdb import Server

    s = Server('http://localhost:5984/')
    db = s['testnotifications']
    # the since parameter defaults to 'last_seq' when using continuous feed
    ch = db.changes(feed='continuous',heartbeat='1000',include_docs=True)

    for line in ch:
        doc = line['doc']
        // process doc here
        doc['priority'] = 'high'
        doc['recipient'] = 'Joe User'
        # doc['state'] + 'sent'
        db.save(doc)

This will allow you access your doc directly from the changes feed, manipulate your data as you see fit, and finally update you document. I use a try/except block on the actual 'db.save(doc)' so I can catch when a document has been updated while I was editing and reload the doc before saving.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!