Supplying CAS to set_multi(), delete_multi() with Python client


#1

Hi folks,

I want to use set_multi and supply CAS values (using the Python client), but could not figure out yet how or if it works.
For example, I tried something like:

items = ItemOptionDict()
for k, v in mydict.items():
    items.add(Item(key=k, value=v['value']), cas=v['cas'])
write_res = couchbase_connection.set_multi(items)

I found a related discussion thread here, but it appears to be not up-to-date.

Many thanks for your help!


#2

I’ve tried to reproduce the example you’ve provided, and it indeed crashes, something it shouldn’t be doing: http://issues.couchbase.com/browse/PYCBC-302 (this is an input validation bug, your example would still fail with an exception if the bug was fixed).

In any event, you should create an Item instance separately, like so:

itm = Item(k, value=v['value'])
itm.cas = v['cas']
items.add(itm)
cb.upsert_multi(items)

The idea behind the Item is that properties bound to the specific document (such as key, value, and cas) remain part of the item, and therefore cas is not an option to the command but rather a property of the input itself.

I might add a create_and_add() method as well, which would let you do what you are doing (as it is indeed the only way to specify CAS in a *multi command)


#3

Cool, Thank you for your fast reply!
I tested it and it worked nicely :smile:

(
For those who are interested: I write it down here because I could not find it in the documentation:
if set_multi fails on a document due to an out-of-date CAS value, it will throw an Error (KeyExistsError err) where err.all_results provides a MultiResult, i.e., you can check individually for each document if it succeeded or not.
)

Many Thanks!


#4

Since version 2.0.0 you can also use the CouchbaseError.split_results() method to give you two dictionaries, one with the successful and one with the failed operations. See http://pythonhosted.org/couchbase/api/exceptions.html#couchbase.exceptions.CouchbaseError.split_results