当前位置: 首页>>代码示例>>Python>>正文


Python couchbase.Couchbase类代码示例

本文整理汇总了Python中couchbase.Couchbase的典型用法代码示例。如果您正苦于以下问题:Python Couchbase类的具体用法?Python Couchbase怎么用?Python Couchbase使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Couchbase类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __call__

 def __call__(self, test, benckmark):
     try:
         self.cbb = Couchbase.connect(bucket='benchmarks', **SHOWFAST)
         self.cbf = Couchbase.connect(bucket='feed', **SHOWFAST)
     except Exception, e:
         logger.warn('Failed to connect to database, {}'.format(e))
         return
开发者ID:abhi-bit,项目名称:perfrunner,代码行数:7,代码来源:reporter.py

示例2: script_main

def script_main(input, output, connection=None, ddoc_name=None):
    if os.path.isdir(input):
        # Read from the filesystem to a design doc, and try to put it into
        # Couchbase. Expects 'input' to be a directory readable by the script,
        # and 'output' to be a set of arguments with which to connect to the
        # Couchbase server.
        cb = connection or Couchbase.connect(**output)
        ddoc = fs_to_ddoc(input)

        # Now on with design documents
        url = ddoc.pop('_id')
        name = url.split('/', 1)[1]  # URL should be "_design/{name}"

        print 'Creating design doc:', name, 'on bucket', output['bucket']
        use_devmode = '_design/dev' in input
        response = cb.design_create(name, ddoc, use_devmode=use_devmode)
        print 'Design doc', name, 'creation result:', response.value
    else:
        # Output to the filesystem from the given input Couchbase instance and
        # the design document name
        cb = connection or Couchbase.connect(**input)
        if not ddoc_name:
            raise AssertionError('No design document name supplied')

        print 'Fetching design doc:', ddoc_name
        response = cb.design_get(ddoc_name, method='GET')
        print 'Design doc', ddoc_name, 'fetch result:', response.value

        ddoc = response
        ddoc_to_fs(ddoc, output)
开发者ID:esplorio,项目名称:fs2couchbase,代码行数:30,代码来源:base.py

示例3: TempDatabaseMixin

class TempDatabaseMixin(object):

    temp_dbs = None
    _db = None

    def setUp(self):
        self.server = Couchbase("localhost", "Administrator", "password")

    def tearDown(self):
        if self.temp_dbs:
            for name in self.temp_dbs:
                self.server.delete(name)

    def temp_db(self):
        if self.temp_dbs is None:
            self.temp_dbs = {}
        # Find an unused database name
        while True:
            name = "couchbase-mapping-python_%d" % random.randint(0, sys.maxint)
            if name not in self.temp_dbs:
                break
        db = self.server.create(name)
        self.temp_dbs[name] = db
        return name, db

    def del_db(self, name):
        del self.temp_dbs[name]
        self.server.delete(name)

    @property
    def db(self):
        if self._db is None:
            name, self._db = self.temp_db()
        return self._db
开发者ID:hdmessaging,项目名称:couchbase-mapping-python,代码行数:34,代码来源:testutil.py

示例4: __call__

 def __call__(self, test, benckmark):
     showfast = test.test_config.stats_settings.showfast
     cbmonitor = test.test_config.stats_settings.cbmonitor
     try:
         self.cbb = Couchbase.connect(bucket='benchmarks', **showfast)
         self.cbf = Couchbase.connect(bucket='feed', **showfast)
     except Exception, e:
         logger.warn('Failed to connect to database, {}'.format(e))
         return
开发者ID:dkao-cb,项目名称:perfrunner,代码行数:9,代码来源:reporter.py

示例5: test_old_unified_client_example

    def test_old_unified_client_example(self):
        from couchbase import Couchbase

        # connect to a couchbase server
        cb = Couchbase(self.host + ':' + self.port,
                       username=self.username,
                       password=self.password)
        if not cb.couch_api_base:
            raise SkipTest

        default_bucket = cb[self.bucket_name]
        default_bucket['key1'] = 'value1'

        default_bucket2 = cb.bucket(self.bucket_name)
        default_bucket2['key2'] = {'value': 'value2', 'expiration': 0}

        default_bucket.set('key3', 0, 0, 'value3')

        self.assertEqual(str(default_bucket.get('key1')[2]), 'value1')
        self.assertEqual(str(default_bucket2.get('key2')[2]), 'value2')
        self.assertEqual(str(default_bucket2['key3'][2]), 'value3')

        # create a new bucket
        try:
            newbucket = cb.create('newbucket', ram_quota_mb=100, replica=1)
        except:
            newbucket = cb['newbucket']

        # set a JSON document using the more "pythonic" interface
        newbucket['json_test'] = {'type': 'item', 'value': 'json test'}
        print 'json_test ' + str(newbucket['json_test'])
        # use the more verbose API which allows for setting expiration & flags
        newbucket.set('key4', 0, 0, {'type': 'item', 'value': 'json test'})
        print 'key4 ' + str(newbucket['key4'])

        design_doc = {"views":
                      {"all_by_types":
                       {"map":
                        '''function (doc, meta) {
                             emit([meta.type, doc.type, meta.id], doc.value);
                             // row output: ['json', 'item', 'key4'], 'json test'
                           }'''
                        },
                       },
                      }
        # save a design document
        newbucket['_design/testing'] = design_doc

        all_by_types_view = newbucket['_design/testing']['all_by_types']
        rows = all_by_types_view.results({'stale': False})
        for row in rows:
            self.assertTrue(row is not None)

        cb.delete('newbucket')
开发者ID:CanWeStudio,项目名称:couchbase-python-client,代码行数:54,代码来源:test_readme_examples.py

示例6: CouchbaseStorage

class CouchbaseStorage(object):
    """
    A storage backend using Couchbase

    You must supply a COUCHBASE_URL setting that is passed through urlparse.
    All parameters supplied get passed through to Couchbase

    Examples:

    * couchbase:///bucket
    * couchbase://hostname/bucket
    * couchbase://host1,host2/bucket
    * couchbase://hostname/bucket?password=123abc&timeout=5
    """
    def __init__(self, settings):
        url = urlparse.urlparse(settings.COUCHBASE_URL)
        params = dict([
            param.split('=')
            for param in url.query.split('&')
        ])
        self.couchbase = Couchbase(host=url.hostname.split(','),
                                   bucket=url.path.strip('/'),
                                   port=url.port or 8091,
                                   **params)

    def save(self, key, value, expire=None):
        res = self.couchbase.set(key, value, ttl=expire)
        return res.success

    def clear(self, key):
        res = self.couchbase.delete(key)
        return res.success

    def clear_all_keys(self):
        """
        Couchbase doesn't support clearing all keys (flushing) without the
        Admin username and password.  It's not appropriate for Will to have
        this information so we don't support clear_all_keys for CB.
        """
        return "Sorry, you must flush the Couchbase bucket from the Admin UI"

    def load(self, key):
        try:
            res = self.couchbase.get(key)
            return res.value
        except cb_exc.NotFoundError:
            pass

    def size(self):
        """
        Couchbase doesn't support getting the size of the DB
        """
        return "Unknown (See Couchbase Admin UI)"
开发者ID:CodeMonk,项目名称:will,代码行数:53,代码来源:couchbase_storage.py

示例7: __init__

 def __init__(
     self,
     priceType="e43",
     echost="api.eve-central.com",
     e43host="element-43.com",
     psqlhost="localhost",
     psqlname="element43",
     psqluser="element43",
     psqlpass="element43",
     psqlport="6432",
     cbserver="127.0.0.1",
     regionID=10000002,
     cbucket="prices",
     cbpass="prices",
 ):
     self.priceType = priceType
     self.echost = echost
     self.e43host = e43host
     self.psqlhost = psqlhost
     self.psqlname = psqlname
     self.psqluser = psqluser
     self.psqlpass = psqlpass
     self.psqlport = psqlport
     self.cache = Couchbase.connect(cbucket, cbserver, password=cbpass)
     self.regionID = int(regionID)
     typeID = 0
开发者ID:Snipa22,项目名称:eveprices,代码行数:26,代码来源:eveprices.py

示例8: get_mult_runs_data

def get_mult_runs_data(design_doc, view_names, x_npy_file, y_npy_file):
    cb = Couchbase.connect(bucket=bucket_name,  host=host_name)

    x = [[0, 0, 0, 0, 0, 0, 0, 0]]

    for view_name in view_names:
        rows = cb.query(design_doc, view_name)

        count = 0
        for row in rows:
            x.append([row.value[1]['thread_alloc_count'],
                      row.value[1]['proc_count'],
                      row.value[1]['thread_alloc_size'],

                      row.value[2]['mem_free'],
                      row.value[2]['native_allocated_heap'],
                      row.value[2]['native_free_heap'],
                      row.value[2]['mem_total'],
                      row.value[2]['native_heap'],

                      row.value[3]['global_class_init'],
                      row.value[3]['classes_loaded'],
                      row.value[3]['total_methods_invoc'],

                      row.value[4]['total_tx'],
                      row.value[4]['total_rx']])

            count = count + 1

            print view_name + ' count: ' + `count`

    x.remove([0, 0, 0, 0, 0, 0, 0, 0])

    joblib.dump(x, x_npy_file)
开发者ID:PSUPing,项目名称:PyExaminer,代码行数:34,代码来源:cb.py

示例9: getbeer

def getbeer(self):
    cb = Couchbase.connect(bucket='beer-sample')
    new_beer = {
        "name": "Old Yankee Ale",
        "abv": 5.00,
        "ibu": 0,
        "srm": 0,
        "upc": 0,
        "type": "beer",
        "brewery_id": "cottrell_brewing_co",
        "updated": "2012-08-30 20:00:20",
        "description": ".A medium-bodied Amber Ale",
        "style": "American-Style Amber",
        "category": "North American Ale"
    }

    try:
        i = 0
        match = randint(0, 100)
        ilimit = 100
        rows = cb.query("beer", "by_name", limit=ilimit, skip=2, include_docs=True)
        for r in rows:
            if r.doc.value != None:
                i += 1
                if i == match:
                    # todo Key mit uebergeben
                    new_beer = r.doc.value
    except CouchbaseError as e:
        print
        e
    finally:
        i = i

    return new_beer
    """
开发者ID:straikongit,项目名称:python,代码行数:35,代码来源:views.py

示例10: get_insight_data

def get_insight_data(request):
    insight = request.GET["insight"]
    abscissa = request.GET["abscissa"]
    vary_by = request.GET.get("vary_by")
    inputs = json.loads(request.GET["inputs"])
    inputs.pop(abscissa)
    if vary_by:
        inputs.pop(vary_by)
    defaults = get_default_inputs(insight)

    cb = Couchbase.connect(bucket="experiments", **settings.COUCHBASE_SERVER)

    data = defaultdict(list)
    for row in cb.query("experiments", "experiments_by_name", key=insight, stale=False):
        value = row.value
        value_inputs = dict(defaults, **value["inputs"])
        if dict(value_inputs, **inputs) == value_inputs:
            key = value["inputs"].get(vary_by, defaults.get(vary_by))
            data[key].append((value_inputs[abscissa], value["value"]))
    for k, v in data.items():
        v.sort(key=lambda xy: xy[0])
    data = OrderedDict(sorted(data.items()))

    content = json.dumps(data)
    return HttpResponse(content)
开发者ID:willCode2Surf,项目名称:cbmonitor,代码行数:25,代码来源:views.py

示例11: connectTOdb

def connectTOdb():
    server = configurations.server_ip
    port = configurations.couchbase_port
    bucket = configurations.couchbase_bucket
    password = configurations.couchbase_password
    cbucket = Couchbase.connect(host=server, port=port, bucket=bucket, password=password)
    return cbucket
开发者ID:anukat2015,项目名称:FITMAN-Anlzer,代码行数:7,代码来源:updateSentimentKeys.py

示例12: get_insight_defaults

def get_insight_defaults(request):
    cb = Couchbase.connect(bucket="exp_defaults", **settings.COUCHBASE_SERVER)
    defaults = [
        row.value for row in cb.query("exp_defaults", "all", stale=False)
    ]
    content = json.dumps(defaults)
    return HttpResponse(content)
开发者ID:willCode2Surf,项目名称:cbmonitor,代码行数:7,代码来源:views.py

示例13: login_user

def login_user(request):
    state = "Please log in below..."
    
    cb=Couchbase.connect(bucket='default', host='localhost')
    
    username = password = ''
    if request.POST:
        
        username = request.POST.get('username')
        password = request.POST.get('password')
        
        try :
            result = cb.get("user::{0}".format(username)).value
            print result
            
            try :
                store = result
                result = json.loads(result)  
            except:
                result = store
                  
            session = {}
        
            if (result['password1'] == password) :
                session['username'] = username
                sessionname = "SessionDetails::{0}".format(username)
                cb.set(sessionname,session)
                
                return render_to_response("deployments.html",{'result':result, 'username' : username})
            else :
                return render_to_response("auth.html",{'error':"IU", 'message':"Your username or password is invalid"})  
        except:
               return render_to_response("auth.html",{'error':"IU", 'message':"Your username or password is invalid"})        
开发者ID:couchbaselabs,项目名称:cloudhosting,代码行数:33,代码来源:views.py

示例14: mngviewAdd

def mngviewAdd(request):
    
    cb=Couchbase.connect(bucket='default', host='localhost')
    
    resultsess = cb.get("SessionDetails::{0}".format(request.POST.get('hiduname'))).value
    username = resultsess['username']
    dep = resultsess['deploymentname']
    
    
    result = cb.get("user::{0}".format(username)).value
    
    print result
  
    deploymentIndex = 0;

    temp ={}
    for res in result['deploy'] :
        if res['request']['depname'] == dep:
            temp = res['request']
            break
        deploymentIndex = deploymentIndex + 1
    
    
    
    temp['status'] = 'RDAD'
    temp['cpus'] = request.POST.get('number')
    temp['deploymentIndex'] = deploymentIndex
    
    depDoc = "DeploymentRequest::{0}::{1}".format(username,timestamp())
    cb.set("{0}".format(depDoc),temp)
    
    resultsess['depDoc'] = depDoc
    cb.set ("SessionDetails::{0}".format(username), resultsess)
    cpu = request.POST.get('number')
    return render_to_response ("progress.html", {'cpu':cpu, 'uname':request.POST.get('hiduname')})
开发者ID:couchbaselabs,项目名称:cloudhosting,代码行数:35,代码来源:views.py

示例15: test_is_instance_of_connection

 def test_is_instance_of_connection(self):
     self.assertIsInstance(
         Couchbase.connect(host=self.host,
                           port=self.port,
                           password=self.bucket_password,
                           bucket=self.bucket_prefix),
         Connection)
开发者ID:neilalbrock,项目名称:couchbase-python-client,代码行数:7,代码来源:test_couchbase.py


注:本文中的couchbase.Couchbase类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。