-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy path04_retrieve.py
87 lines (68 loc) · 1.92 KB
/
04_retrieve.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/usr/bin/env python
# -*- coding" utf-8 -*-
import os
from couchbase import Couchbase
from couchbase.exceptions import KeyExistsError
from blessings import Terminal
import json
import hashlib
# establish connection
cb = Couchbase.connect(bucket="default")
def parse_json( val ):
vtype = type(val[2])
if vtype is str:
try:
json_doc = json.loads(val[2])
return json_doc
except:
print
return val[2]
t = Terminal()
os.system('clear')
print t.bold_red("--------------------------------------------------------------------------")
print t.bold_red("Couchbase JSON Document Retrieve Operations")
print t.bold_red("--------------------------------------------------------------------------")
print
user_data1 = \
{
"doctype": "learn",
"username": "jsmith",
"name": "John Smith",
"email": "[email protected]",
"password": "p4ssw0rd",
"logins": 0
}
user_data2 = \
{
"doctype": "learn",
"username": "xsmith",
"name": "Xavier Smith",
"email": "[email protected]",
"password": "p4ssw0rd",
"logins": 0
}
print t.bold("Set 2 User Docs")
print
# initialize the documents
cb.set(user_data1["email"], user_data1)
cb.set(user_data2["email"], user_data2)
# retrieve the document and output
print t.bold("Retrieve Doc and Inspect CAS")
print
kv = cb.get(user_data1["email"])
print kv
print t.bold_red("--------------------------------------------------------------------------")
print t.bold_red("Update doc and look at cas")
print
kv.value["logins"] += 1
cb.replace(kv.value["email"], kv.value, cas=kv.cas)
kv = cb.get(user_data1["email"])
print kv
print t.bold_red("--------------------------------------------------------------------------")
print t.bold_red("Data Consistency: Try to update with invalid CAS")
print ""
try:
cb.replace(kv.value["email"], kv.value, cas=0xdeadbeef)
except KeyExistsError as e:
print e
print t.bold_red("--------------------------------------------------------------------------")