本文整理汇总了Python中couchbase.bucket.Bucket.upsert方法的典型用法代码示例。如果您正苦于以下问题:Python Bucket.upsert方法的具体用法?Python Bucket.upsert怎么用?Python Bucket.upsert使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类couchbase.bucket.Bucket
的用法示例。
在下文中一共展示了Bucket.upsert方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: confirm_ir
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import upsert [as 别名]
def confirm_ir(request, ir_id, group_id, user_id):
print("IR CONFIRMATION")
c = Bucket('couchbase://localhost/nihongo')
user_doc = c.get(user_id).value
password = user_doc['password']
ir_doc = c.get(ir_id).value
if 'accept' in request.POST:
print("IR ACCEPTED")
ir_doc['confirmed'] = 'accepted'
sync_user = SyncGateway.get_user(user_id)
new_sync_user = {}
admin_channels = sync_user['admin_channels']
#all_channels = sync_user['all_channels']
admin_channels.append(group_id)
SyncGateway.put_user(sync_user['name'], '[email protected]', password, admin_channels)
print(sync_user)
elif 'decline' in request.POST:
ir_doc['confirmed'] = 'declined'
print("IR DECLINED")
c.upsert(ir_id, ir_doc)
return HttpResponseRedirect(reverse('tutor:tutor_groups'))
示例2: post
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import upsert [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}))
示例3: test_function_where_handler_code_takes_more_time_to_execute_than_execution_timeout
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import upsert [as 别名]
def test_function_where_handler_code_takes_more_time_to_execute_than_execution_timeout(self):
keys = ['customer123', 'customer1234', 'customer12345']
url = 'couchbase://{ip}/{name}'.format(ip=self.master.ip, name=self.src_bucket_name)
bucket = Bucket(url, username="cbadminbucket", password="password")
for doc_id in keys:
bucket.upsert(doc_id, {'name' : doc_id})
# create a function which sleeps for 5 secs and set execution_timeout to 1s
body = self.create_save_function_body(self.function_name, HANDLER_CODE_ERROR.EXECUTION_TIME_MORE_THAN_TIMEOUT,
execution_timeout=1)
# deploy the function
self.deploy_function(body)
# This is intentionally added so that we wait for some mutations to process and we decide none are processed
self.sleep(60)
# No docs should be present in dst_bucket as the all the function executions should have timed out
self.verify_eventing_results(self.function_name, 0, skip_stats_validation=True)
eventing_nodes = self.get_nodes_from_services_map(service_type="eventing", get_all_nodes=True)
exec_timeout_count = 0
for eventing_node in eventing_nodes:
rest_conn = RestConnection(eventing_node)
out = rest_conn.get_all_eventing_stats()
# get sum of all timeout_count
exec_timeout_count += out[0]["failure_stats"]["timeout_count"]
# check whether all the function executions timed out and is equal to number of docs created
if exec_timeout_count != len(keys):
self.fail("Not all event executions timed out : Expected : {0} Actual : {1}".format(len(keys),
exec_timeout_count))
self.undeploy_and_delete_function(body)
示例4: _update_document
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import upsert [as 别名]
def _update_document(self, key, document):
url = 'couchbase://{ip}/default'.format(ip=self.master.ip)
if self.upgrade_to.startswith("4"):
bucket = Bucket(url)
else:
bucket = Bucket(url, username="default", password="password")
bucket.upsert(key, document)
示例5: test_add_concurrent
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import upsert [as 别名]
def test_add_concurrent(self):
DOCID = 'subdoc_doc_id'
CONNSTR = 'couchbase://' + self.servers[0].ip + ':11210'
ITERATIONS = 200
THREADS = 20
main_bucket = SDK_Bucket(CONNSTR)
main_bucket.upsert(DOCID, {'recs':[]})
thrs = []
class Runner(Thread):
def run(self, *args, **kw):
cb = SDK_Bucket(CONNSTR)
for x in range(ITERATIONS):
cb.mutate_in(DOCID, SD.array_append('recs', 1))
thrs = [Runner() for x in range(THREADS)]
[t.start() for t in thrs]
[t.join() for t in thrs]
obj = main_bucket.get(DOCID)
array_entry_count = len(obj.value['recs'])
self.assertTrue( array_entry_count == ITERATIONS * THREADS,
'Incorrect number of array entries. Expected {0} actual {1}'.format(ITERATIONS * THREADS,
array_entry_count))
示例6: register
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import upsert [as 别名]
def register(request):
args = {}
args.update(csrf(request))
args['form'] = UserCreationForm()
if request.POST:
newuser_form = UserCreationForm(request.POST)
if newuser_form.is_valid():
newuser_form.save()
newuser = auth.authenticate(username=newuser_form.cleaned_data['username'], password=newuser_form.cleaned_data['password2'])
auth.login(request, newuser)
#Adding user to main bucket
try:
c = Bucket('couchbase://localhost/nihongo')
username = newuser_form.cleaned_data['username']
password = newuser_form.cleaned_data['password2']
c_username = 'user_' + username
new_user = {'username' : username, 'password' : password, 'doc_type' : 'user_doc'}
doc_channels = [c_username]
new_user['doc_channels'] = doc_channels
c.upsert(c_username, new_user)
except CouchbaseError as ce:
raise Http404("Couchbase server error")
#Adding user to sync gateway database
SyncGateway.put_user(c_username, '[email protected]', password, [c_username])
return redirect('/')
else:
args['form'] = newuser_form
return render_to_response('register.html', args)
示例7: parseAndSave
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import upsert [as 别名]
def parseAndSave(s):
for l in s.find (id="data_list").findAll("tr"):
try:
tagALinkToDetail = l.find(has_link_to_show_php)
if tagALinkToDetail:
fullText=tagALinkToDetail.text.strip()
logger.info("Searching info in douban with keyword: %s" % fullText)
m = Movie(fullText)
m.source_link = tagALinkToDetail['href']
m.numberOfSeeds=int(tagALinkToDetail.parent.parent.find(class_='bts_1').text)
m.source_link=str(tagALinkToDetail["href"])
bucket = Bucket('couchbase://localhost/default')
v=json.dumps(m.__dict__)
bucket.upsert(fullText,v)
else:
logger.debug("skip a line in mp4ba resource page, most likely because it is an ads")
except AttributeError as ae:
logger.error (ae)
logger.error ("Error! Skipped when trying to parse: %s" % l)
exit
except Exception as e:
logger.error (e)
logger.error ("Error! Skipped when trying to parse: %s" % l)
exit
示例8: test_transcoder_class
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import upsert [as 别名]
def test_transcoder_class(self):
# Test whether we can pass a class for a transcoder
key = self.gen_key("transcoder_class")
c = Bucket(**self.make_connargs(transcoder=TranscoderPP))
c.upsert(key, "value")
c = Bucket(**self.make_connargs(transcoder=TranscoderPP))
c.upsert(key, "value")
示例9: request_invite
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import upsert [as 别名]
def request_invite(request, user_id, group_id):
default = 'request for invite from' + user_id
request_text = request.POST.get('request_text', default)
c = Bucket('couchbase://localhost/nihongo')
invite_request = {'doc_type' : 'invite_request', 'user_id' : user_id, 'group_id' : group_id}
invite_request['request_text'] = request_text
invite_request['confirmed'] = "pending"
ireq ='ireq_' + str(uuid4()).replace('-', '_')
c.upsert(ireq, invite_request)
return HttpResponseRedirect(reverse('tutor:tutor_groups'))
示例10: update_profile
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import upsert [as 别名]
def update_profile(request):
try:
user_dict = request.GET
users_bucket = Bucket('couchbase://localhost/users_us')
if 'uid' in user_dict:
users_bucket.upsert(request.GET.get('uid'), user_dict)
return HttpResponse("successfully updated user profile")
else:
return HttpResponseBadRequest('uid not found')
except Exception, e:
return HttpResponseServerError("internal server error. Error : {e}".format(e=str(e)))
示例11: _upload_test_run_dailyp
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import upsert [as 别名]
def _upload_test_run_dailyp(self, test_run_dict):
try:
bucket = Bucket('couchbase://{}/perf_daily'
.format(StatsSettings.CBMONITOR))
except Exception as e:
logger.info("Post to Dailyp, DB connection error: {}".format(e.message))
return False
doc_id = "{}__{}__{}__{}__{}".format(test_run_dict['category'],
test_run_dict['subcategory'],
test_run_dict['test'],
test_run_dict['build'],
test_run_dict['datetime'])
bucket.upsert(doc_id, test_run_dict)
return True
示例12: cb_loader
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import upsert [as 别名]
def cb_loader(_tid, _total_threads, _key_prefix, _key_start, _key_end, _a1_selectivity, _value_size, _connection_string):
print ("Starting Thread %s" % _tid)
#establish connection
print ("Connecting: ", _connection_string)
b = Bucket(_connection_string)
for i in range( _key_start, _key_end):
if (i % _total_threads == _tid):
t0 = time.clock()
b.upsert( _key_prefix + str(i),
{'a1': (i) % _a1_selectivity, 'a2': "Zero".zfill(_value_size)},
replicate_to=0,
persist_to=0)
t1 = time.clock()
print ("Thread: " + str(_tid) + ". Last execution time in milliseond: %3.3f" % ((t1 - t0) * 1000))
示例13: CouchbaseManager
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import upsert [as 别名]
class CouchbaseManager(Manager):
def __init__(self, bucket):
from couchbase.bucket import Bucket
self.bucket = Bucket('couchbase://{}/{}'.format(
os.environ.get('CB_HOST'), bucket))
self.bucket.timeout = 30
def set(self, key, value):
self.bucket.upsert(key, value)
def get(self, key):
from couchbase.exceptions import NotFoundError
try:
return self.bucket.get(key).value
except NotFoundError:
raise FileNotFoundError()
示例14: process_line
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import upsert [as 别名]
def process_line(line_to_process):
data = json.loads(line_to_process)
collection = data["path"]["collection"]
key = data["path"]["key"] or 'NOTHING'
document = data['value']
account_alias = document.get('accountAlias', None)
document_name = collection.lower()
if account_alias and document_name in documents_to_exclude and account_alias in accounts_to_exclude:
#print key + '-->' + document_name + '-->' + account_alias + '-->EXCLUDED********'
return
document['_class'] = class_list[document_name]
#print key + '-->' + collection
try:
cb = Bucket('couchbase://' + couch_host + '/' + couch_bucket, password=couch_pass)
cb.upsert(key, document)
except Exception as e:
print 'Failed to process : {0} --> {1}. Error {2}'.format(key, collection, e.message)
failed_file.write(line_to_process)
示例15: MatchHistoryUpdater
# 需要导入模块: from couchbase.bucket import Bucket [as 别名]
# 或者: from couchbase.bucket.Bucket import upsert [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)