Beispiel #1
0
def create_bucket(name: str, memory: int, admin: Admin) -> int:
    try:
        admin.bucket_create(name, ram_quota=memory)
    except HTTPError as err:
        v = err.__dict__['all_results'][None]
        if v.value['errors'] and 'name' in v.value[
                'errors'] and 'already exists' in v.value['errors']['name']:
            print('%s bucket already exists, not creating.' % name)
        else:
            print(err)
        return 1
    return 0
def ensure_create_bucket(username: str,
                         password: str,
                         bucket_name: str,
                         host="couchbase",
                         port="8091"):
    adm = Admin(username, password, host=host, port=port)
    try:
        adm.bucket_create(bucket_name, bucket_type="couchbase")
        return True
    except HTTPError as e:
        if (e.objextra.value["errors"]["name"] ==
                "Bucket with given name already exists"):
            return True
Beispiel #3
0
    def test_connection_string_param(self):

        conn_str = 'http://{0}:{1}'.format(self.cluster_info.host, self.cluster_info.port)
        admin = Admin('Administrator',
                      'password',
                      connection_string=conn_str)
        self.assertIsNotNone(admin)
Beispiel #4
0
 def cluster_manager(self):
     """
     Returns an instance of :class:`~.couchbase.admin.Admin` which may be
     used to create and manage buckets in the cluster.
     """
     username, password = self.authenticator.get_credentials()
     return Admin(username, password)
Beispiel #5
0
    def test_bucket_param(self):

        admin = Admin('Administrator',
                      'password',
                      host=self.cluster_info.host,
                      port=self.cluster_info.port,
                      bucket='default')
        self.assertIsNotNone(admin)
 def cluster_manager(self):
     """
     Returns an instance of :class:`~.couchbase.admin.Admin` which may be
     used to create and manage buckets in the cluster.
     """
     credentials = self.authenticator.get_credentials()['options']
     connection_string = str(self.connstr)
     return Admin(credentials.get('username'),
                  credentials.get('password'),
                  connection_string=connection_string)
import pytest
import unittest

from instana.singletons import tracer
from ..helpers import testenv, get_first_span_by_name, get_first_span_by_filter

from couchbase.admin import Admin
from couchbase.cluster import Cluster
from couchbase.bucket import Bucket
from couchbase.exceptions import CouchbaseTransientError, HTTPError, KeyExistsError, NotFoundError
import couchbase.subdocument as SD
from couchbase.n1ql import N1QLQuery

# Delete any pre-existing buckets.  Create new.
cb_adm = Admin(testenv['couchdb_username'],
               testenv['couchdb_password'],
               host=testenv['couchdb_host'],
               port=8091)

# Make sure a test bucket exists
try:
    cb_adm.bucket_create('travel-sample')
    cb_adm.wait_ready('travel-sample', timeout=30)
except HTTPError:
    pass


@pytest.mark.skipif("COUCHBASE_TEST" not in os.environ, reason="")
class TestStandardCouchDB(unittest.TestCase):
    def setup_class(self):
        """ Clear all spans before a test run """
        self.recorder = tracer.recorder
)
app.config.from_object(app_settings)

# init couchbase connection
import json
from couchbase.admin import Admin
from couchbase.exceptions import HTTPError
from couchbase.cluster import Cluster, Bucket
from couchbase.cluster import PasswordAuthenticator
from couchbase.analytics import AnalyticsQuery

# Initialize couchbase connection and ensure required buckets exist
ip : str = 'localhost'
print('Connecting to Couchbase instance at %s' % (ip))

adm = Admin('Administrator', 'password', host=ip, port=8091)

create_bucket('media', 750, adm)
create_bucket('users', 100,adm)

adm._close()

# connect to buckets
cb_cluster : Cluster = Cluster('couchbase://localhost?operation_timeout=4')
authenticator : PasswordAuthenticator = PasswordAuthenticator('Administrator', 'password')
cb_cluster.authenticate(authenticator)
cb_media : Bucket = cb_cluster.open_bucket('media')
cb_users : Bucket = cb_cluster.open_bucket('users')

# register blueprints
from project.server.views.home import home_bp
Beispiel #9
0
 def make_admin_connection(self):
     return Admin(self.username, self.password, self.host, self.port)
Beispiel #10
0
#!/usr/bin/env - python

from couchbase.admin import Admin

import settings

# Settings
bucket_name = settings.BUCKET_NAME
node = settings.CLUSTER_NODES[0]
admin_user = settings.ADMIN_USER
admin_password = settings.ADMIN_PASS
timeout = settings.TIMEOUT

if __name__ == '__main__':
    sdk_admin = Admin(admin_user, admin_password, host=node)
    print("Cleaning up bucket {0}...".format(bucket_name))
    sdk_admin.bucket_remove(bucket_name)
    print("Clean up finished!")

user='******'
password='******'
if len(sys.argv)==3:
  host = sys.argv[1]
  bucket = sys.argv[2]

else:
  print "usage: "+sys.argv[0]+" host bucket"
  exit(1)


#make an administrative connection using Admin object
try:
    admin = Admin(username=user,password=password,host=host,port=8091)
except CouchbaseError as e:
    print " Sorry , we could not create admin connection , due to " , e
else :
    print "Successfully made an admin connection "


#retrieve bucket information for bucket named "default" 
#   "default" is just the name of the bucket I set up for trying this out
try:
    htres = admin.http_request("/pools/default/buckets/"+bucket)
except Exception as e:
    print "ERROR: ", e
    sys.exit()

print "number of items before flush: ", htres.value['basicStats']['itemCount']
Beispiel #12
0
import json
from couchbase.admin import Admin
from couchbase.exceptions import HTTPError
from couchbase.cluster import Cluster
from couchbase.cluster import PasswordAuthenticator
from couchbase.analytics import AnalyticsQuery

# The terraform script will out put the IP address
ip_f = open('terraform/ip_address.txt')
ip = str(ip_f.read()).strip('\n')

print('Connecting to Couchbase instance at %s' % (ip))

adm = Admin('Administrator', 'password', host=ip, port=8091)

try:
    adm.bucket_create('commerce')
except HTTPError as err:
    v = err.__dict__['all_results'][None]
    if 'already exists' in v.value['errors']['name']:
        print('Bucket already exists, not creating.')

adm.wait_ready('commerce', timeout=10)

# connect w/ SDK
cluster = Cluster('couchbase://' + ip)
auth = PasswordAuthenticator('Administrator', 'password')
cluster.authenticate(auth)
cb = cluster.open_bucket('commerce')

# create anlytics indexes
Beispiel #13
0
def get_info():
    name = input("Insert name: ")
    age = input("Insert age: ")
    height = input("Insert height in inches: ")
    weight = input("Insert weight in lbs: ")
    email = input("Insert email: ")
    phone = input("Insert phone number: ")
    return name, age, height, weight, email, phone


cluster = Cluster('http://127.0.0.1:8091')
authenticator = PasswordAuthenticator('corbinmatamoros', 'MattCorbin')
cluster.authenticate(authenticator)

adm = Admin('corbinmatamoros', 'MattCorbin', host='localhost', port=8091)
# adm.bucket_create('class-bucket',bucket_type='couchbase')

#open the 'travel-bucket' within the cluster 'cluster'
bucket1 = cluster.open_bucket('class-bucket')

n, a, h, w, e, p = get_info()

bucket1.upsert(
    n, {
        'age': a,
        'height_in': h,
        'weight_lbs': w,
        'contact_info': {
            'email': e,
            'phone': p
Beispiel #14
0
cb.upsert('user6', user3)
cb.remove('user6')  # supprime document
cb.upsert('user6', user6)
cb.get('user6', ttl=0)  # change ttl
cb.touch('user6', ttl=60)  #idem
cb.get('user6')

# 4
doc = ['user1', 'user2', 'user3', 'user4']
gm = cb.get_multi(doc)
for key, result in gm.items():
    print "Value is", result.value

# création bucket
from couchbase.admin import Admin
adm = Admin('Julie', 'CBD1jg', host='localhost')
adm.bucket_create('TP4', bucket_type='couchbase', ram_quota=100)

# génération de 1000 documents à la volée fichier dans le cache
cb = cluster.open_bucket('TP4')
documents = {}
for i in range(1000):
    documents['user' + str(i)] = {
        'ID': 's' + str(i),
        'type': 'spy',
        'login': '******' + str(i),
        'mdp': 'mission' + str(i)
    }

cb.upsert_multi(documents)
def get_bucket_stats(bucket_name='default'):
    admin = Admin(COUCHBASE_USERNAME, COUCHBASE_PASSWORD, COUCHBASE_HOSTS[0])
    return admin.bucket_info(bucket_name).value['basicStats']
Beispiel #16
0
 def test_bad_host(self):
     # admin connections don't really connect until an action is performed
     admin = Admin('username', 'password', host='127.0.0.1', port=1)
     self.assertRaises(CouchbaseNetworkError, admin.bucket_info, 'default')
Beispiel #17
0
    url = "http://{0}:8094/api/index/{1}".format(node, fts_index_name)
    payload = json.load(fts_json)
    headers = {'content-type': 'appllication.json'}
    x = requests.put(url,
                     data=json.dumps(payload),
                     headers=headers,
                     timeout=timeout,
                     auth=HTTPBasicAuth(admin_user, admin_password))
    if x.status_code == 200:
        print("Indexes created successfully!")
    else:
        print(
            "!!! Error creating indexes:\n{0}\nExecute cleanup.py and try again"
            .format(x.text))


if __name__ == '__main__':
    sdk_admin = Admin(admin_user, admin_password, host=node)
    admin_create_bucket(sdk_admin)
    # Workaround wait_ready is not enough...
    time.sleep(timeout)
    sdk_client = Bucket('couchbase://{0}/{1}'.format(node, bucket_name),
                        username=user,
                        password=password)
    sdk_client.timeout = timeout
    add_stocks(sdk_client)
    cluster = Cluster('couchbase://{0}'.format(node),
                      ClusterOptions(PasswordAuthenticator(user, password)))
    cluster.query_indexes().create_primary_index(bucket_name)
    add_fts_indexes()
from couchbase.cluster import Cluster, PasswordAuthenticator
from couchbase.exceptions import NotFoundError, KeyExistsError
from couchbase.result import OperationResult, ValueResult
from couchbase.admin import Admin
import couchbase.subdocument as subdoc

SERVER_IP = "137.112.89.94"

cluster = Cluster('couchbase://{}:8091'.format(SERVER_IP))
__authenticator = PasswordAuthenticator('admin2', 'An3WeeWa')
cluster.authenticate(__authenticator)

adm = Admin('admin', 'An3WeeWa', host=SERVER_IP, port=8091)


class Buckets():
    offering_bucket = cluster.open_bucket('offerings')
    schedule_bucket = cluster.open_bucket('schedules')
    user_bucket = cluster.open_bucket('users')
    course_bucket = cluster.open_bucket('courses')

    _all = [offering_bucket, schedule_bucket, user_bucket, course_bucket]
    _timeout = 2.000

    for bucket in _all:
        bucket.timeout = _timeout


if __name__ == '__main__':
    bckt = input("Enter bucket name to create: ")
    if not bckt:
Beispiel #19
0
import sys

sys.path.append("/usr/lib64/python3.7/site-packages")

import couchbase

print(couchbase.__version__)

from couchbase.admin import Admin

adm = Admin("Administrator", "123456", host="localhost", port=8091)

# https://docs.couchbase.com/python-sdk/2.4/managing-connections.html#connecting-to-a-bucket
from couchbase.cluster import Cluster
from couchbase.cluster import PasswordAuthenticator

import os

docker_host = os.environ["DOCKER_HOST"]
print("couchbase://{0}".format(docker_host))

cluster = Cluster("couchbase://{0}".format(docker_host))

authenticator = PasswordAuthenticator("Administrator", "123456")
cluster.authenticate(authenticator)


bucket = cluster.open_bucket("bucket_1")


bucket.upsert(
Beispiel #20
0
 def make_admin_connection(self):
     return Admin(self.admin_username,
                  self.admin_password,
                  self.host,
                  self.port,
                  ipv6=self.ipv6)
Beispiel #21
0
from couchbase.cluster import Cluster
from couchbase.cluster import PasswordAuthenticator
from couchbase.admin import Admin  # the admin class gives me the power to create/delete buckets
from couchbase.n1ql import N1QLQuery

cluster = Cluster('couchbase://*****:*****@couchbase.com',
        'interests': ['Holy Grail', 'African Swallows']
    })
# OperationResult<RC=0x0, Key=u'u:king_arthur', CAS=0xb1da029b0000>

cb.get('u:king_arthur').value
# {u'interests': [u'Holy Grail', u'African Swallows'], u'name': u'Arthur', u'email': u'*****@*****.**'}

## The CREATE PRIMARY INDEX step is only needed the first time you run this script
cb.n1ql_query('CREATE PRIMARY INDEX ON `swallows-sample`').execute()
row_iter = cb.n1ql_query(N1QLQuery('SELECT name FROM `swallows-sample` WHERE ' +\
'$1 IN interests', 'African Swallows'))
for row in row_iter:
#!/usr/bin/env python

from couchbase.admin import Admin
from couchbase.bucket import Bucket

adm = Admin('Administrator', '123456', host='localhost', port=8091)
adm.bucket_create('new-bucket',
                  bucket_type='couchbase',
                  bucket_password='******')

# Wait for bucket to become ready
adm.wait_ready('new-bucket', timeout=30)

bucket = Bucket('couchbase://localhost/new-bucket', password='******')
bucket.upsert('foo', 'bar')

adm.bucket_remove('new-bucket')
Beispiel #23
0
 def test_bad_host(self):
     if sys.version_info >= (3, 6) and sys.platform.startswith('linux'):
         raise SkipTest("To be fixed on Linux 3.6")
     # admin connections don't really connect until an action is performed
     admin = Admin('username', 'password', host='127.0.0.1', port=1)
     self.assertRaises(CouchbaseNetworkError, admin.bucket_info, 'default')
def flush_bucket(bucket_name='default'):
    admin = Admin(COUCHBASE_USERNAME, COUCHBASE_PASSWORD, COUCHBASE_HOSTS[0])
    return admin.http_request(
        '/pools/default/buckets/%s/controller/doFlush' % bucket_name, 'POST')