本文整理汇总了Python中couchbase.bucket.Bucket.insert方法的典型用法代码示例。如果您正苦于以下问题:Python Bucket.insert方法的具体用法?Python Bucket.insert怎么用?Python Bucket.insert使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类couchbase.bucket.Bucket
的用法示例。
在下文中一共展示了Bucket.insert方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: post
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import insert [as 别名]
def post(self, request, group_id):
c = Bucket('couchbase://localhost/nihongo')
success = 'dunno'
constgroup = group_id.rsplit('_', 1)[0]
print(constgroup)
print('adding new deck')
try:
description = request.POST['description']
print(description)
ckey = 'deck_' + str(uuid4()).replace('-', '_')
newdeck = {'doc_type' : 'deck', 'description' : description, 'deck_name' : description}
newdeck['cards_list'] = []
newdeck['doc_channels'] = [group_id]
c.insert(ckey, newdeck)
group = c.get(group_id).value
print(group.get('decks_list'))
group.get('decks_list').append(ckey)
c.upsert(group_id, group)
success = 'success'
except (BaseException, CouchbaseError) as e:
success = 'error'
print(e)
group = c.get(group_id).value
group_decks = group.get('decks_list')
decks_list = []
for d in group_decks:
try:
deck = c.get(d)
decks_list.append(deck)
except CouchbaseError:
pass
return HttpResponseRedirect(reverse('tutor:group_decks', kwargs={'group_id' : group_id}))
示例2: test_eventing_processes_mutations_when_mutated_through_subdoc_api_and_set_expiry_through_sdk
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import insert [as 别名]
def test_eventing_processes_mutations_when_mutated_through_subdoc_api_and_set_expiry_through_sdk(self):
# set expiry pager interval
ClusterOperationHelper.flushctl_set(self.master, "exp_pager_stime", 1, bucket=self.src_bucket_name)
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.insert(docid, {'some': 'value'})
body = self.create_save_function_body(self.function_name, self.handler_code,
dcp_stream_boundary="from_now")
# deploy eventing function
self.deploy_function(body)
# upserting a new sub-document
bucket.mutate_in('customer123', SD.upsert('fax', '775-867-5309'))
# inserting a sub-document
bucket.mutate_in('customer1234', SD.insert('purchases.complete', [42, True, None], create_parents=True))
# Creating and populating an array document
bucket.mutate_in('customer12345', SD.array_append('purchases.complete', ['Hello'], create_parents=True))
self.verify_eventing_results(self.function_name, 3, skip_stats_validation=True)
for docid in ['customer123', 'customer1234', 'customer12345']:
# set expiry on all the docs created using sub doc API
bucket.touch(docid, ttl=5)
self.sleep(10, "wait for expiry of the documents")
# Wait for eventing to catch up with all the expiry mutations and verify results
self.verify_eventing_results(self.function_name, 0, skip_stats_validation=True)
self.undeploy_and_delete_function(body)
示例3: MatchHistoryUpdater
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import insert [as 别名]
class MatchHistoryUpdater(object):
def __init__(self):
self.riot = riotwatcher.RiotWatcher(
default_region=riotwatcher.EUROPE_WEST,
key=os.environ.get('RIOT_API_KEY'))
self.bucket = Bucket('couchbase://{}/{}'.format(
os.environ.get('DB_HOST', 'localhost'),
os.environ.get('DB_BUCKET_MATCH_HISTORY', 'match_history')
))
self.players = self.get_players()
logger_datapop.info('Setup complete')
while True:
for player in self.players:
self.update_recent_games(player['id'])
time.sleep(SLEEP_TIME)
self.players = self.get_players()
def get_players(self):
players = [row.doc.value for row in self.bucket.query(
'player', 'all_players', stale=False, include_docs=True)]
return players
def update_recent_games(self, player_id):
api_matches = self.riot.get_recent_games(player_id)['games']
for match in api_matches:
match['summonerId'] = player_id
key = 'Match::{}::{}'.format(player_id, match['gameId'])
try:
self.bucket.insert(key, match)
except cb_exceptions.KeyExistsError:
break
try:
full_match = self.riot.get_match(match_id=match['gameId'],
include_timeline=True)
time.sleep(SLEEP_TIME)
except Exception:
continue
else:
full_match_key = 'Match::{}'.format(match['gameId'])
self.bucket.upsert(full_match_key, full_match)
示例4: initialize_game_rules_bucket
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import insert [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)
示例5: considerado
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import insert [as 别名]
# nao sera considerado (geralmente eh uma desfiliacao
# a pedido e outra via judicial)
chave = "-".join((
linha['NUMERO DA INSCRICAO'],
linha['DATA DA FILIACAO'],
linha['SITUACAO DO REGISTRO'],
))
dados = {
'type': 'filiado',
'titulo_eleitor': linha['NUMERO DA INSCRICAO'],
'nome': linha['NOME DO FILIADO'],
'sigla_partido': linha['SIGLA DO PARTIDO'],
'situacao_registro': linha['SITUACAO DO REGISTRO'],
'tipo_registro': linha['TIPO DO REGISTRO'],
'zona_eleitoral': linha['SECAO ELEITORAL'],
'secao_eleitoral': linha['ZONA ELEITORAL'],
'codigo_municipio': linha['CODIGO DO MUNICIPIO'],
'uf': linha['UF'],
'data_filiacao': linha['DATA DA FILIACAO'],
}
if linha['DATA DO CANCELAMENTO']:
dados['data_cancelamento'] = linha['DATA DO CANCELAMENTO']
if linha['DATA DA DESFILIACAO']:
dados['data_desfiliacao'] = linha['DATA DA DESFILIACAO']
try:
bucket.insert(chave, dados)
except KeyExistsError:
# pula o registro
continue
示例6: SDKClient
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import insert [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:
#.........这里部分代码省略.........
示例7: TeamSpeak
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import insert [as 别名]
records[record[0]] = record[1]
teamspeak = TeamSpeak(records["host"], records["port"])
parser = QueryParser()
teamspeak.authenticate(records["username"], records["password"])
teamspeak.select_server(records["serverid"])
channels = parser.parse(teamspeak.query(b"channellist"))
clients = parser.parse(teamspeak.query(b"clientlist"))
output_data = {"channels" : channels, "clients" : clients}
bucket = Bucket("couchbase://localhost/default")
# print(json.dumps(output_data))
bucket.insert(str(int(time.time())), output_data)
# reply_data = parser.parse(teamspeak.query(b"clientlist"))
# reply_data = parser.parse(teamspeak.query(b"channellist"))
# pprint.pprint(reply_data)
# raw_users = reply_data.split(b"|")
# visited_channels = set()
# for data in raw_users:
# userdata = data.split(b" ")
# for client_data in userdata:
# if b"cid=" in client_data:
# channel_id = client_data.split(b"=")[1]
示例8: DB
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import insert [as 别名]
class DB(object):
def __init__(self, bucket):
self.bucket = bucket
self.db = Bucket(bucket, lockmode=LOCKMODE_WAIT)
def doc_exists(self, docId):
try:
result = self.db.get(docId)
except CouchbaseError as e:
return False
return result
def insert_build_history(self, build, update=False):
try:
docId = build['version']+"-"+str(build['build_num'])
if update:
result = self.db.upsert(docId, build)
else:
result = self.db.insert(docId, build)
logger.debug("{0}".format(result))
except CouchbaseError as e:
if e.rc == 12:
logger.warning("Couldn't create build history {0} due to error: {1}".format(docId, e))
docId = None
return docId
def insert_distro_history(self, distro, update=False):
try:
docId = distro['version']+"-"+str(distro['build_num'])+"-"+distro['distro']+"-"+distro['edition']
if update:
result = self.db.upsert(docId, distro)
else:
result = self.db.insert(docId, distro)
logger.debug("{0}".format(result))
except CouchbaseError as e:
if e.rc == 12:
logger.warning("Couldn't create distro history {0} due to error: {1}".format(docId, e))
docId = None
return docId
def insert_test_history(self, unit, test_type='unit', update=False):
try:
if test_type == 'unit':
docId = unit['version']+"-"+str(unit['build_num'])+"-"+unit['distro']+"-"+unit['edition']+'-tests'
elif test_type == 'build_sanity':
docId = unit['version']+"-"+str(unit['build_num'])+"-"+unit['distro']+"-"+unit['edition']+'-sanity-tests'
if update:
result = self.db.upsert(docId, unit)
else:
result = self.db.insert(docId, unit)
logger.debug("{0}".format(result))
except CouchbaseError as e:
if e.rc == 12:
logger.warning("Couldn't create test history {0} due to error: {1}".format(docId, e))
docId = None
return docId
def insert_commit(self, commit):
docId = commit['repo']+"-"+str(commit['sha'])
inb = commit['in_build'][0]
try:
result = self.db.get(docId)
val = result.value
if not inb in val['in_build']:
val['in_build'].append(inb)
result = self.db.upsert(docId, val)
except CouchbaseError as e:
if e.rc == 13:
try:
result = self.db.insert(docId, commit)
logger.debug("{0}".format(result))
except CouchbaseError as e:
print e.rc
if e.rc == 12:
logger.error("Couldn't create commit history {0} due to error: {1}".format(docId, e))
docId = None
return docId
def update_distro_result(self, docId, distroId, result):
try:
ret = self.db.get(docId).value
if not distroId in ret[result]:
ret[result].append(distroId)
if result != 'incomplete':
if distroId in ret['incomplete']:
ret['incomplete'].remove(distroId)
self.db.upsert(docId, ret)
logger.debug("{0}".format(result))
except CouchbaseError as e:
logger.warning("Couldn't update distro result on {0} due to error: {1}".format(docId, e))
docId = None
return
#.........这里部分代码省略.........
示例9: putJson
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import insert [as 别名]
def putJson(self, json, id):
bucket = Bucket(self._bucketUrl)
bucket.insert(str(id), json)
示例10: put
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import insert [as 别名]
def put(self, object, id):
bucket = Bucket(self._bucketUrl)
bucket.insert(id.urn[9:], json.loads(object))
示例11: buildDB
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import insert [as 别名]
class buildDB(object):
def __init__(self, bucket):
self.bucket = bucket
self.db = Bucket(bucket, lockmode=LOCKMODE_WAIT)
def insert_job_history(self, job):
#
# param: job
# type: dict
#
try:
docId = job['branch']+"-"+str(job['buildNum'])+"-"+job['platform']+"-"+job['edition']
result = self.db.insert(docId, job)
logger.debug("{0}".format(result))
except CouchbaseError as e:
if e.rc == 12:
logger.warning("Couldn't create job history {0} due to error: {1}".format(docId, e))
return docId
def update_job_history(self, job):
#
# param: job
# type: dict
#
try:
docId = job['branch']+"-"+str(job['buildNum'])+"-"+job['platform']+"-"+job['edition']
result = self.db.replace(docId, job)
logger.debug("{0}".format(result))
except CouchbaseError as e:
if e.rc == 13:
logger.error("Couldn't update job history. {0} does not exist {1}".format(docId, e))
def insert_build_history(self, bldHistory):
#
# param: bldHistory
# type: dict
#
# Job history should be inserted prior to this
#
try:
docId = bldHistory['branch']+"-"+str(bldHistory['buildNum'])
result = self.db.insert(docId, bldHistory)
logger.debug("{0}".format(result))
except CouchbaseError as e:
if e.rc == 12:
logger.warning("Couldn't create build history {0} due to error: {1}".format(docId, e))
return docId
def update_build_history(self, bldHistory):
try:
docId = bldHistory['branch']+"-"+str(bldHistory['buildNum'])
result = self.db.replace(docId, bldHistory)
logger.debug("{0}".format(result))
except CouchbaseError as e:
if e.rc == 13:
logger.error("Couldn't update build history {0} does not exist {1}".format(docId, e))
def insert_commit(self, commit):
try:
docId = commit['repo']+"-"+str(commit['commitId'])
result = self.db.insert(docId, commit)
logger.debug("{0}".format(result))
except CouchbaseError as e:
if e.rc == 12:
logger.error("Couldn't create commit history {0} due to error: {1}".format(docId, e))
return docId
def query_commit(self, commitId):
readResult = self.db.get(commitId)
return readResult.value
def find_prev_build(self, dashboard_name, criteria="undefined"):
logger.debug("Not implemented")
bldNum = 0
return bldNum
def retrieve_incomplete_builds(self, dashboard_name):
# Get previously incomplete builds
logger.debug("{0}...not implemented".format(dashboard_name))
def query_buildHistory(self, bldHistory):
docId = bldHistory['branch']+"-"+str(bldHistory['buildNum'])
readResult = self.db.get(docId)
return readResult.value
def __repr__(self):
return ("buildDB(history, num_jobs)".format(self))
示例12: Bucket
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import insert [as 别名]
from couchbase.bucket import Bucket
import couchbase.exceptions as E
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:
示例13: CouchbaseMemcacheMirror
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import insert [as 别名]
#.........这里部分代码省略.........
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)
def touch(self, key, expire=0):
st = Status()
try:
self.cb.touch(key, ttl=expire)
except NotFoundError as e:
st.cb_error = st
st.mc_status = self.mc.touch(key)
def set(self, key, value, expire=0):
"""
Write first to Couchbase, and then to Memcached
:param key: Key to use
:param value: Value to use
:param expire: If set, the item will expire in the given amount of time
:return: Status object if successful (will always be success).
on failure an exception is raised
"""
self.cb.upsert(key, value, ttl=expire)
self.mc.set(key, value, expire=expire)
return Status()
def set_multi(self, values, expire=0):
"""
Set multiple items.
:param values: A dictionary of key, value indicating values to store
:param expire: If present, expiration time for all the items
:return:
"""
self.cb.upsert_multi(values, ttl=expire)
self.mc.set_many(values, expire=expire)
return Status()
def replace(self, key, value, expire=0):
"""
Replace existing items
:param key: key to replace
:param value: new value
:param expire: expiration for item
:return: Status object. Will be OK
"""
status = Status()
try:
self.cb.replace(key, value, ttl=expire)
except NotFoundError as e:
status.cb_error = e
status.mc_status = self.mc.replace(key, value, expire=expire)
return status
def add(self, key, value, expire=0):
status = Status()
try:
self.cb.insert(key, value, ttl=expire)
except KeyExistsError as e:
status.cb_error = e
status.mc_status = self.mc.add(key, value, expire=expire)
return status
def _append_prepend(self, key, value, is_append):
cb_meth = self.cb.append if is_append else self.cb.prepend
mc_meth = self.mc.append if is_append else self.mc.prepend
st = Status()
try:
cb_meth(key, value, format=FMT_UTF8)
except (NotStoredError, NotFoundError) as e:
st.cb_error = e
st.mc_status = mc_meth(key, value)
def append(self, key, value):
return self._append_prepend(key, value, True)
def prepend(self, key, value):
return self._append_prepend(key, value, False)
def cas(self, key, value, cas, expire=0):
if self._primary == PRIMARY_COUCHBASE:
try:
self.cb.replace(key, value, cas=cas, ttl=expire)
self.mc.set(key, value, ttl=expire)
return True
except KeyExistsError:
return False
except NotFoundError:
return None
else:
return self.mc.cas(key, value, cas)
开发者ID:couchbaselabs,项目名称:sk-python-couchbase-memcache-mirror,代码行数:104,代码来源:couchbase_memcache_mirror.py
示例14: SessionStore
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import insert [as 别名]
class SessionStore(SessionBase):
"""
A couchbase-based session store.
"""
def __init__(self, session_key=None):
super(SessionStore, self).__init__(session_key)
host = settings.COUCHBASE_HOST
bucket = settings.COUCHBASE_BUCKET
self.server = Bucket('couchbase://' + host + '/' + bucket)
@property
def cache_key(self):
return self._get_or_create_session_key()
def load(self):
try:
session_data = self.server.get(
self._get_or_create_session_key()
)
return session_data.value
except:
self._session_key = None
return {}
def create(self):
while True:
self._session_key = self._get_new_session_key()
try:
self.save(must_create=True)
except CreateError:
continue
self.modified = True
return
def save(self, must_create=False):
if self.session_key is None:
return self.create()
if must_create and self.exists(self._get_or_create_session_key()):
raise CreateError
if must_create:
data = self._get_session(no_load=must_create)
self.server.insert(
self._get_or_create_session_key(),
data
)
else:
data = self._get_session(no_load=must_create)
self.server.replace(
self._get_or_create_session_key(),
data
)
def exists(self, session_key):
rv = self.server.get(session_key, quiet=True)
return rv.success
def delete(self, session_key=None):
if session_key is None:
if self.session_key is None:
return
session_key = self.session_key
try:
self.server.remove(session_key)
except:
pass
@classmethod
def clear_expired(cls):
pass