Listen to database changes
couchdbkit 0.6.0 introduced a new API to listen for CouchDB changes.
The `couchdbkit.changes` modules allows you to listen for changes with a
streaming API.
Stream changes in your application:
To listen for change, instantiate the `couchdbkit.changes.ChangesStream`
object and iterrate it:
from couchdbkit import Server
from couchdbkit.changes import ChangesStream, fold, foreach
s = Server()
db = s['testdb’]
stream = ChangesStream(db, feed=“continuous”, heartbeat=True)
print “got change now”
for change in stream:
print change
You can also use it as a context:
from couchdbkit import Server
from couchdbkit.changes import ChangesStream, fold, foreach
s = Server()
db = s['testdb’]
with ChangesStream(db, feed=“continuous”, heartbeat=True) as stream:
for change in stream:
print change
Note: if you want to use it with gevent, you can just setup a gevent
pool:
from couchdbkit import Server
from couchdbkit.changes import ChangesStream, fold, foreach
from restkit.conn import Connection
from socketpool.pool import ConnectionPool
pool = ConnectionPool(factory=Connection, backend=“gevent”)
s = Server(pool=pool)
db = s['testdb’]
with ChangesStream(db, feed=“continuous”, heartbeat=True) as stream:
for change in stream:
print change
For more information about creating a greened pool, read the href=“http://benoitc.github.com/restkit/green.html”>restkit
documentation.
You can of course spawn or do anything you want with the gevent or
eventlet libraries.
fold changes:
`couchdbkit.changes.fold` allows you to fold all changes and pass
the change to a function, while collecting results to an accumularor.
The accumulator is returned at the end of the changes.
Exemple to fetch all changes in a streaming fashion:
def fold_fun(c, acc):
acc.append©
return acc
acc = fold(db, fold_fun, [])
Note: The function take an optionnal `since` parameter.
Iterrate all changes
`couchdbkit.changes.foreach` allows you to itterate all changes and pass
the change to a function:
def print_change©:
print c
foreach(db, print_change)
Note: The function take an optionnal `since` parameter.