本文整理汇总了Python中couchbase.bucket.Bucket.remove方法的典型用法代码示例。如果您正苦于以下问题:Python Bucket.remove方法的具体用法?Python Bucket.remove怎么用?Python Bucket.remove使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类couchbase.bucket.Bucket
的用法示例。
在下文中一共展示了Bucket.remove方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: purgeDisabled
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import remove [as 别名]
def purgeDisabled(job, bucket):
client = Bucket(HOST+'/'+bucket)
name = job["name"]
bids = [b["number"] for b in job["builds"]]
high_bid = bids[0]
for bid in xrange(high_bid):
# reconstruct doc id
bid = bid + 1
oldKey = "%s-%s" % (name, bid)
oldKey = hashlib.md5(oldKey).hexdigest()
# purge
try:
client.remove(oldKey)
except Exception as ex:
print "[WARN] did not find disabled job to delete: [%s-%s]" % (name,bid)
pass # delete ok
示例2: delete_couchbase_server_cached_rev_bodies
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import remove [as 别名]
def delete_couchbase_server_cached_rev_bodies(self, bucket):
"""
Deletes docs that follow the below format
_sync:rev:att_doc:34:1-e7fa9a5e6bb25f7a40f36297247ca93e
"""
b = Bucket("couchbase://{}/{}".format(self.host, bucket))
cached_rev_doc_ids = []
b.n1ql_query("CREATE PRIMARY INDEX ON `{}`".format(bucket)).execute()
for row in b.n1ql_query("SELECT meta(`{}`) FROM `{}`".format(bucket, bucket)):
if row["$1"]["id"].startswith("_sync:rev"):
cached_rev_doc_ids.append(row["$1"]["id"])
log_info("Found temp rev docs: {}".format(cached_rev_doc_ids))
for doc_id in cached_rev_doc_ids:
log_debug("Removing: {}".format(doc_id))
b.remove(doc_id)
示例3: test_sorted_removed_items_indexed
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import remove [as 别名]
def test_sorted_removed_items_indexed(self):
if self.plasma_dgm:
self.get_dgm_for_plasma(indexer_nodes=[self.dgmServer])
generators = self._upload_documents_in_sorted()
self.full_docs_list = self.generate_full_docs_list(generators)
self.gen_results = TuqGenerators(self.log, self.full_docs_list)
query_definition = QueryDefinition(
index_name="index_range_shrink_name",
index_fields=["name"],
query_template="SELECT * FROM %s WHERE name IS NOT NULL",
groups=["simple"], index_where_clause=" name IS NOT NULL ")
buckets = []
for bucket in self.buckets:
if bucket.name.startswith("plasma_dgm"):
buckets.append(bucket)
self.multi_create_index(buckets=buckets,
query_definitions=[query_definition])
self.sleep(30)
intervals = [["d", "e", "f"], ["j", "k", "l", "m"], ["p", "q", "r", "s"] ]
temp_list = []
for doc_gen in self.full_docs_list:
for interval in intervals:
for character in interval:
if doc_gen["name"].lower().startswith(character):
for bucket in buckets:
url = "couchbase://{0}/{1}".format(self.master.ip,
bucket.name)
cb = Bucket(url, username=bucket.name, password="password")
cb.remove(doc_gen["_id"])
temp_list.append(doc_gen)
if not self.multi_intervals:
break
self.full_docs_list = [doc for doc in self.full_docs_list if doc not in temp_list]
self.gen_results = TuqGenerators(self.log, self.full_docs_list)
self.multi_query_using_index(buckets=buckets,
query_definitions=[query_definition])
self.sleep(30)
self.multi_drop_index(buckets=buckets,
query_definitions=[query_definition])
示例4: test_eventing_processes_mutation_when_xattrs_is_updated
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import remove [as 别名]
def test_eventing_processes_mutation_when_xattrs_is_updated(self):
url = 'couchbase://{ip}/{name}'.format(ip=self.master.ip, name=self.src_bucket_name)
bucket = Bucket(url, username="cbadminbucket", password="password")
for docid in ['customer123', 'customer1234', 'customer12345']:
bucket.upsert(docid, {})
body = self.create_save_function_body(self.function_name, self.handler_code,
dcp_stream_boundary="from_now")
# deploy eventing function
self.deploy_function(body)
# update multiple xattrs and update the documents
for docid in ['customer123', 'customer1234', 'customer12345']:
bucket.mutate_in(docid, SD.upsert('my1', {'value': 1}, xattr=True))
bucket.mutate_in(docid, SD.upsert('my2', {'value': 2}, xattr=True))
bucket.mutate_in(docid, SD.upsert('fax', '775-867-5309'))
self.verify_eventing_results(self.function_name, 3, skip_stats_validation=True)
# add new multiple xattrs , delete old xattrs and delete the documents
for docid in ['customer123', 'customer1234', 'customer12345']:
bucket.mutate_in(docid, SD.upsert('my3', {'value': 3}, xattr=True))
bucket.mutate_in(docid, SD.upsert('my4', {'value': 4}, xattr=True))
bucket.mutate_in(docid, SD.remove('my3', xattr=True))
bucket.mutate_in(docid, SD.remove('my4', xattr=True))
bucket.remove(docid)
self.verify_eventing_results(self.function_name, 0, skip_stats_validation=True)
self.undeploy_and_delete_function(body)
示例5: initialize_game_rules_bucket
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import remove [as 别名]
def initialize_game_rules_bucket(bucket=None):
if bucket is None:
bucket = Bucket("couchbase://localhost/game_rules")
# Create the game document for super mario bro's
smb = {
"file_name": "/home/mcsmash/dev/nestopia/smb.nes",
"system": "NES",
"name": "Super Mario Brothers and Duck Hunt",
}
try:
bucket.insert("game:1", smb)
except KeyExistsError:
pass
sprite_list = []
for i, fn in enumerate(glob("/home/mcsmash/dev/data/game_playing/sprites/*")):
extensionless = os.path.splitext(os.path.basename(fn))
sprite_list.append({"id": extensionless, "path": os.path.abspath(fn)})
try:
bucket.insert("sprites:1", sprite_list)
except KeyExistsError:
pass
try:
bucket.remove("game_number")
except NotFoundError:
pass
try:
bucket.remove("play_number:1")
except NotFoundError:
pass
bucket.counter("game_number", initial=2)
bucket.counter("play_number:1", initial=1)
示例6: purge
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import remove [as 别名]
def purge(bucket, known_jobs):
client = Bucket(HOST+'/'+bucket)
DDOC='/'.join([VIEW_API,bucket,'_design',bucket,'_view'])
BUILDS_Q = DDOC+"/data_by_build?full_set=true&group_level=1&inclusive_end=true&reduce=true&stale=false"
ALL_PLATFORMS = []
ALL_COMPONENTS = []
# purger for all platforms+comonent combo of each build
r = getReq(BUILDS_Q)
if r is None:
return
data = r.json()
rows = data.get('rows')
if rows is None:
print "No data for: "+bucket
return
for row in rows:
build = row['key'][0]
if not build:
continue
url = DDOC+"/jobs_by_build?startkey=%22"+build+"%22&endkey=%22"+build+"_%22&inclusive_end=true&reduce=false&stale=false"
r = getReq(url)
if r is None:
continue
data = r.json()
# all jobs
JOBS = {}
if not data.get('rows'): continue
for job in data['rows']:
_id = str(job['id'])
val = job['value']
name = val[0]
os = val[1]
comp = val[2]
url = val[3]
cnt = val[5]
bid = val[6]
isExecutor = False
url_noauth = None
if url.find("@") > -1: # url has auth, clean
url_noauth = "http://"+url.split("@")[1]
if url.find("test_suite_executor") > -1:
isExecutor = True
if comp in ["UNIT","BUILD_SANITY"]:
continue # don't purge build jobs
# if job is unknown try to manually get url
url_find = url_noauth or url
if url_find not in known_jobs and not isExecutor:
r = getReq(url)
if r is None:
continue
if r.status_code == 404:
try:
client.remove(_id)
print "****MISSING*** %s_%s: %s:%s:%s (%s,%s)" % (build, _id, os, comp, name, val[5], bid)
except:
pass
continue
if os in JOBS:
if comp in JOBS[os]:
match = [(i, n) for i, n in enumerate(JOBS[os][comp]) if n[0] == name]
if len(match) > 0:
idx = match[0][0]
oldBid = match[0][1][1]
oldDocId = match[0][1][2]
if oldBid > bid:
# purge this docId because it is less this saved bid
try:
client.remove(_id)
print "****PURGE-KEEP*** %s_%s: %s:%s:%s (%s,%s < %s)" % (build, _id, os, comp, name, val[5], bid, oldBid)
except:
pass
else:
# bid must exist in prior to purge replace
r = getReq(url+"/"+str(bid))
if r is None:
continue
if r.status_code == 404:
# delete this newer bid as it no longer exists
try:
client.remove(_id)
except:
pass
else:
# purge old docId
#.........这里部分代码省略.........
示例7: SDKClient
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import remove [as 别名]
class SDKClient(object):
"""Python SDK Client Implementation for testrunner - master branch Implementation"""
def __init__(self, bucket, hosts = ["localhost"] , scheme = "couchbase",
ssl_path = None, uhm_options = None, password=None,
quiet=True, certpath = None, transcoder = None):
self.connection_string = \
self._createString(scheme = scheme, bucket = bucket, hosts = hosts,
certpath = certpath, uhm_options = uhm_options)
self.password = password
self.quiet = quiet
self.transcoder = transcoder
self.default_timeout = 0
self._createConn()
def _createString(self, scheme ="couchbase", bucket = None, hosts = ["localhost"], certpath = None, uhm_options = ""):
connection_string = "{0}://{1}".format(scheme, ", ".join(hosts).replace(" ",""))
if bucket != None:
connection_string = "{0}/{1}".format(connection_string, bucket)
if uhm_options != None:
connection_string = "{0}?{1}".format(connection_string, uhm_options)
if scheme == "couchbases":
if "?" in connection_string:
connection_string = "{0},certpath={1}".format(connection_string, certpath)
else:
connection_string = "{0}?certpath={1}".format(connection_string, certpath)
return connection_string
def _createConn(self):
try:
self.cb = CouchbaseBucket(self.connection_string, password = self.password,
quiet = self.quiet, transcoder = self.transcoder)
self.default_timeout = self.cb.timeout
except BucketNotFoundError as e:
raise
def reconnect(self):
self.cb.close()
self._createConn()
def close(self):
self.cb._close()
def counter_in(self, key, path, delta, create_parents=True, cas=0, ttl=0, persist_to=0, replicate_to=0):
try:
return self.cb.counter_in(key, path, delta, create_parents= create_parents, cas= cas, ttl= ttl, persist_to= persist_to, replicate_to= replicate_to)
except CouchbaseError as e:
raise
def arrayappend_in(self, key, path, value, create_parents=True, cas=0, ttl=0, persist_to=0, replicate_to=0):
try:
return self.cb.arrayappend_in(key, path, value, create_parents=create_parents, cas=cas, ttl=ttl, persist_to=persist_to, replicate_to=replicate_to)
except CouchbaseError as e:
raise
def arrayprepend_in(self, key, path, value, create_parents=True, cas=0, ttl=0, persist_to=0, replicate_to=0):
try:
return self.cb.arrayprepend_in(key, path, value, create_parents=create_parents, cas=cas, ttl=ttl, persist_to=persist_to, replicate_to=replicate_to)
except CouchbaseError as e:
raise
def arrayaddunique_in(self, key, path, value, create_parents=True, cas=0, ttl=0, persist_to=0, replicate_to=0):
try:
return self.cb.addunique_in(key, path, value, create_parents=create_parents, cas=cas, ttl=ttl, persist_to=persist_to, replicate_to=replicate_to)
except CouchbaseError as e:
raise
def arrayinsert_in(self, key, path, value, cas=0, ttl=0, persist_to=0, replicate_to=0):
try:
return self.cb.arrayinsert_in(key, path, value, cas=cas, ttl=ttl, persist_to=persist_to, replicate_to=replicate_to)
except CouchbaseError as e:
raise
def remove_in(self, key, path, cas=0, ttl=0):
try:
self.cb.remove_in(key, path, cas = cas, ttl = ttl)
except CouchbaseError as e:
raise
def mutate_in(self, key, *specs, **kwargs):
try:
self.cb.mutate_in(key, *specs, **kwargs)
except CouchbaseError as e:
raise
def lookup_in(self, key, *specs, **kwargs):
try:
self.cb.lookup_in(key, *specs, **kwargs)
except CouchbaseError as e:
raise
def get_in(self, key, path):
try:
result = self.cb.get_in(key, path)
return self.__translate_get(result)
except CouchbaseError as e:
raise
def exists_in(self, key, path):
try:
#.........这里部分代码省略.........
示例8: print
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import remove [as 别名]
# Store a document
rv = cb.upsert('first', {'hello': 'world'})
cas = rv.cas
print(rv)
# Get the document
item = cb.get('first')
print(item)
# Overwrite the existing document only if the CAS value matched
try:
# An exception will be raised if the CAS doesn't match
wrong_cas = cas + 123
cb.upsert('first', {'hello': 'world', 'additional': True}, cas=wrong_cas)
except KeyExistsError:
# Get the correct current CAS value
rv = cb.get('first')
item, flags, correct_cas = rv.value, rv.flags, rv.cas
# Set it again, this time with the correct CAS value
rv = cb.upsert('first',
{'hello': 'world', 'additional': True},
cas=correct_cas)
print(rv)
# Delete the document only if the CAS value matches (it would also
# work without a cas value)
cb.remove('first', cas=rv.cas)
# Make sure the document really got deleted
assert cb.get('first', quiet=True).success is False
示例9: test_eventing_where_dataset_has_different_key_types_using_sdk_and_n1ql
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import remove [as 别名]
def test_eventing_where_dataset_has_different_key_types_using_sdk_and_n1ql(self):
keys = [
"1324345656778878089435468780879760894354687808797613243456567788780894354687808797613243456567788780894354687808797613243456567788780894354687808797613287808943546878087976132434565677887808943546878087976132434565677887808943546878087976132943546878",
# max key size
"1", # Numeric key, see MB-26706
"a1", # Alphanumeric
"1a", # Alphanumeric
"1 a b", # Alphanumeric with space
"1.234", # decimal
"~`[email protected] #$%^&*()-_=+{}|[]\:\";\'<>?,./", # all special characters
"\xc2\xa1 \xc2\xa2 \xc2\xa4 \xc2\xa5", # utf-8 encoded characters
"true", # boolean key
"false", # boolean key
"True", # boolean key
"False", # boolean key
"null", # null key
"undefined", # undefined key
# Check here for javascript builtin objects : https://mzl.la/1zDsM8O
"NaN",
"Symbol()",
"Symbol(42)"
"Symbol(\'foo\')",
"isNaN",
"Error",
"Function",
"Infinity",
"Atomics",
"Boolean",
"ArrayBuffer",
"DataView",
"Date",
"Generator {}",
"InternalError",
"Intl",
"Number",
"Math",
"Map",
"Promise",
"Proxy"
]
url = 'couchbase://{ip}/{name}'.format(ip=self.master.ip, name=self.src_bucket_name)
bucket = Bucket(url, username="cbadminbucket", password="password")
for key in keys:
bucket.upsert(key, "Test with different key values")
# create a doc using n1ql query
query = "INSERT INTO " + self.src_bucket_name + " ( KEY, VALUE ) VALUES ('key11111','from N1QL query')"
self.n1ql_helper.run_cbq_query(query=query, server=self.n1ql_node)
body = self.create_save_function_body(self.function_name, self.handler_code)
self.deploy_function(body)
# Wait for eventing to catch up with all the update mutations and verify results
self.verify_eventing_results(self.function_name, len(keys) + 1, skip_stats_validation=True)
# delete all the documents with different key types
for key in keys:
bucket.remove(key)
# delete a doc using n1ql query
self.n1ql_helper.create_primary_index(using_gsi=True, server=self.n1ql_node)
query = "DELETE FROM " + self.src_bucket_name + " where meta().id='key11111'"
self.n1ql_helper.run_cbq_query(query=query, server=self.n1ql_node)
# Wait for eventing to catch up with all the delete mutations and verify results
self.verify_eventing_results(self.function_name, 0, skip_stats_validation=True)
self.undeploy_and_delete_function(body)
self.n1ql_helper.drop_primary_index(using_gsi=True, server=self.n1ql_node)
示例10: purge
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import remove [as 别名]
def purge(bucket, known_jobs):
client = Bucket(HOST+'/'+bucket)
DDOC='/'.join([VIEW_API,bucket,'_design',bucket,'_view'])
BUILDS_Q = DDOC+"/data_by_build?full_set=true&group_level=1&inclusive_end=true&reduce=true&stale=false"
ALL_PLATFORMS = []
ALL_COMPONENTS = []
# purger for all platforms+comonent combo of each build
r = requests.get(BUILDS_Q)
data = r.json()
for row in data['rows']:
build = row['key'][0]
if not build:
continue
url = DDOC+"/jobs_by_build?startkey=%22"+build+"%22&endkey=%22"+build+"_%22&inclusive_end=true&reduce=false&stale=false"
r = requests.get(url)
data = r.json()
# all jobs
JOBS = {}
if not data.get('rows'): continue
for job in data['rows']:
_id = str(job['id'])
val = job['value']
name = val[0]
os = val[1]
comp = val[2]
url = val[3]
cnt = val[5]
bid = val[6]
if url.find("test_suite_executor") > -1:
# no purging on executor
continue
print "Process: %s" % (name)
# if job is unknown try to manually get url
if url not in known_jobs:
r = requests.get(url)
if r.status_code == 404:
print "****MISSING*** %s_%s: %s:%s:%s (%s,%s)" % (build, _id, os, comp, name, val[5], bid)
client.remove(_id)
continue
if os in JOBS:
if comp in JOBS[os]:
match = [(i, n) for i, n in enumerate(JOBS[os][comp]) if n[0] == name]
if len(match) > 0:
idx = match[0][0]
oldBid = match[0][1][1]
oldDocId = match[0][1][2]
if oldBid > bid:
# purge this docId because it is less this saved bid
client.remove(_id)
print "****PURGE-KEEP*** %s_%s: %s:%s:%s (%s,%s < %s)" % (build, _id, os, comp, name, val[5], bid, oldBid)
else:
# bid must exist in prior to purge replace
if requests.get(url+"/"+str(bid)).status_code == 404:
# delete this newer bid as it no longer exists
client.remove(_id)
else:
# purge old docId
client.remove(oldDocId)
# use this bid as new tracker
JOBS[os][comp][idx] = (name, bid, _id)
print "****PURGE-REPLACE*** %s_%s: %s:%s:%s (%s,%s > %s)" % (build, _id, os, comp, name, val[5], bid, oldBid)
continue
else:
# append to current comp
JOBS[os][comp].append((name,bid, _id))
else:
# new comp
JOBS[os][comp] = [(name, bid, _id)]
else:
# new os
JOBS[os] = {}
JOBS[os][comp] = [(name, bid, _id)]
示例11: storeBuild
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import remove [as 别名]
def storeBuild(url):
view = BUILD_VIEW
client = Bucket(HOST+'/server')
job = getJS(url)
if not job:
print "No job info for build"
return
result = job.get("result")
if not result:
return
actions = job["actions"]
totalCount = getAction(actions, "totalCount") or 0
failCount = getAction(actions, "failCount") or 0
skipCount = getAction(actions, "skipCount") or 0
if totalCount == 0:
return
params = getAction(actions, "parameters")
os = getAction(params, "name", "DISTRO") or job["fullDisplayName"].split()[2].split(",")[0]
version = getAction(params, "name", "VERSION")
build = getAction(params, "name", "CURRENT_BUILD_NUMBER") or getAction(params, "name", "BLD_NUM")
if not (version or build):
return
build = version+"-"+build.zfill(4)
name=os+"_watson-unix"
if getAction(params, "name", "UNIT_TEST"):
name += "_unit"
os, comp = getOsComponent(name, view)
if not os or not comp:
return
duration = int(job["duration"]) or 0
# lookup pass count fail count version
doc = {
"build_id": int(job["id"]),
"claim": "",
"name": name,
"url": url,
"component": comp,
"failCount": failCount,
"totalCount": totalCount,
"result": result,
"duration": duration,
"priority": "P0",
"os": os,
"build": build
}
key = "%s-%s" % (doc["name"], doc["build_id"])
print key+","+build
key = hashlib.md5(key).hexdigest()
try:
if version == "4.1.0":
# not tracking, remove and ignore
client.remove(key)
else:
client.upsert(key, doc)
except Exception as ex:
print "set failed, couchbase down?: %s %s" % (HOST, ex)
示例12: Bucket
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import remove [as 别名]
from __future__ import print_function
import random
import os
from couchbase.bucket import Bucket
from couchbase.n1ql import N1QLQuery, CONSISTENCY_REQUEST
# Ensure there is a primary index on the default bucket!
RANDOM_NUMBER = random.randint(0, 10000000)
cb = Bucket('couchbase://10.0.0.31/default')
cb.upsert('user:{}'.format(RANDOM_NUMBER), {
'name': ['Brass', 'Doorknob'],
'email': ['[email protected]'],
'random': RANDOM_NUMBER
})
query = N1QLQuery(
'SELECT name, email, random, META(default).id FROM default WHERE $1 IN name', 'Brass')
# If this line is removed, the latest 'random' field might not be present
query.consistency = CONSISTENCY_REQUEST
print('Expecting random:', RANDOM_NUMBER)
for row in cb.n1ql_query(query):
print('Name: {0}, Email: {1}, Random: {2}'.format(row['name'], row['email'], row['random']))
if row['random'] == RANDOM_NUMBER:
print('!!! Found our newly inserted document !!!')
if os.environ.get('REMOVE_DOORKNOBS'):
cb.remove(row['id'])
示例13: Bucket
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import remove [as 别名]
#!/usr/bin/env python
from __future__ import print_function
from couchbase.bucket import Bucket
cb = Bucket('couchbase://10.0.0.31/default')
# Remove document so we have predictable behavior in this example
# the 'quiet' argument instructs the client not to raise an exception if the
# document doesn't exist, but fail silently (the status can still be retrieved
# from the returned result object)
cb.remove('docid', quiet=True)
# Without the 'initial' parameter, this command would fail if the item doesn't exist
rv = cb.counter('docid', delta=20, initial=100)
print('Delta=20, Initial=100. Current value is:', rv.value)
rv = cb.counter('docid', delta=1)
print('Delta=1. Current value is:', rv.value)
rv = cb.counter('docid', delta=-50)
print('Delta=-50. Current value is:', rv.value)
示例14: Bucket
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import remove [as 别名]
cb = Bucket('couchbase://10.0.0.31/default')
# This always works!
print('Upserting')
cb.upsert('docid', {'property': 'value'})
print('Getting item back. Value is:',
cb.get('docid').value)
print('...')
print('Will try to insert the document. Should fail because the item already exists..')
try:
cb.insert('docid', {'property': 'value'})
except E.KeyExistsError:
print('Insert failed because item already exists!')
print('...')
print('Replacing the document. This should work because the item already exists')
cb.replace('docid', {'property': 'new_value'})
print('Getting document again. Should contain the new contents:',
cb.get('docid').value)
print('...')
print('Removing document.')
# Remove the item, then try to replace it!
cb.remove('docid')
print('Replacing document again. Should fail because document no longer exists')
try:
cb.replace('docid', {'property': 'another value'})
except E.NotFoundError:
print('Get failed since item does not exist')
示例15: CouchbaseMemcacheMirror
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import remove [as 别名]
#.........这里部分代码省略.........
def gets(self, key):
"""
Get an item with its CAS. The item will always be fetched from the primary
data store.
:param key: the key to get
:return: the value of the key, or None if no such value
"""
if self._primary == PRIMARY_COUCHBASE:
try:
rv = self.cb.get(key)
return key, rv.cas
except NotFoundError:
return None, None
else:
return self.mc.gets(key)
def gets_multi(self, keys):
if self._primary == PRIMARY_COUCHBASE:
try:
rvs = self.cb.get_multi(keys)
except NotFoundError as e:
rvs, _ = e.split_results()
return {k: (v.value, v.cas) for k, v in rvs}
else:
# TODO: I'm not sure if this is implemented in HasClient :(
return self.mc.gets_many(keys)
def delete(self, key):
st = Status()
try:
self.cb.remove(key)
except NotFoundError as e:
st.cb_error = e
st.mc_status = self.mc.delete(key)
return st
def delete_multi(self, keys):
st = Status()
try:
self.cb.remove_multi(keys)
except NotFoundError as e:
st.cb_error = e
st.mc_status = self.mc.delete_many(keys)
def _do_incrdecr(self, key, value, is_incr):
cb_value = value if is_incr else -value
mc_meth = self.mc.incr if is_incr else self.mc.decr
st = Status()
try:
self.cb.counter(key, delta=cb_value)
except NotFoundError as e:
st.cb_error = e
st.mc_status = mc_meth(key, value)
def incr(self, key, value):
return self._do_incrdecr(key, value, True)
def decr(self, key, value):
return self._do_incrdecr(key, value, False)
开发者ID:couchbaselabs,项目名称:sk-python-couchbase-memcache-mirror,代码行数:69,代码来源:couchbase_memcache_mirror.py