Couchbase III(Python Library)

第一步

安装

使用pip安装:

>pip install couchbase --quiet

确认是否安装成功:

>python -c "import couchbase"

API 第一印象

from couchbase import Couchbase
from couchbase.exceptions import CouchbaseError c = Couchbase.connect(bucket='beer-sample', host='localhost') try:
beer = c.get("aass_brewery-juleol") except CouchbaseError as e:
print "Couldn't retrieve value for key", e
# Rethrow the exception, making the application exit
raise doc = beer.value # Because Python 2.x will complain if an ASCII format string is used
# with Unicode format values, we make the format string unicode as well. print unicode("{name}, ABV: {abv}").format(name=doc['name'], abv=doc['abv']) doc['comment'] = "Random beer from Norway" try:
result = c.replace("aass_brewery-juleol", doc)
print result except CouchbaseError as e:
print "Couldn't replace key"
raise

存储文档

基本操作

  • set(key, value)

    Stores the document value under the key.
    If the key did not previously exist, it is created.
    If the key already exists, its existing value is overwritten with the new contents of value.
  • add(key, value)

    Stores the document value under the key, but only if key does not already exist.
    If key already exists, an exception is thrown.
  • replace(key, value)

    Replace is the inverse of add.
    It sets the contents of key to value, but only if the key already exists.
    If the key does not already exist, an exception is thrown.
  • delete(key)

    Deletes the key from the bucket.
    Future attempts to access this key via get raise an exception until something is stored again
    for this key using one of the set methods.

获取文档

获取单文档
#无异常处理
client.store("my list", [])
result = client.get("my list")
doc = result.value #异常处理版, 单请求
result = client.get("non-exist-key", quiet=True)
if result.success:
print "Got document OK"
else:
print ("Couldn't retrieve document. "
"Result was received with code"), result.rc #异常处理版,所有连接请求
client = Couchbase.connect(bucket='default', quiet=True)
result = client.get("non-exist-key")
if result.success:
print "Got document OK"
else:
print "Couldn't retrieve document"

获取多文档

client.set_multi({
'sheep_counting' : ['first sheep', 'second sheep'],
'famous_sheep' : {'sherry lewis' : 'Lamb Chop'}
})
keys = ('sheep_counting', 'famous_sheep')
results = client.get_multi(keys)
for key, result in results.items():
doc = result.value #异常处理版
results = client.get_multi(("i exist", "but i don't"), quiet=True)
#迭代判断
for key results:
if result.success:
print "Got document OK"
doc = result.value
else:
print "Couldn't retrieve document"
#一次判断所有
#if not results.all_ok:
#print "Couldn't get all keys"
异常处理

文档不存在时 ,抛出 couchbase.exceptions.NotFoundError

使用 Connection.quiet 可以改变异常处理的行为

获取View
results = client.query("beer", "brewery_beers",
include_docs=True, limit=5)
for result in results:
print "key is %r" % (result.key)
doc = result.doc.value
if doc['type'] == "beer":
print "Got a beer. It's got %0.2f ABV" % (doc['abv'],)
  • include_docs

    This boolean parameter indicates whether the corresponding document should be retrieved
    for each row fetched.
    If this is true, the doc property of the ViewRow object yielded by the iterator returned
    by query contains a Result object that contains the document for the key.
  • reduce

    This boolean parameter indicates whether the server should also pass the results to
    the view’s reduce function.
    An exception is raised if the view does not have a reduce method defined.
  • limit

    This numeric parameter indicates the maximum amount of results to fetch from the query.
    This parameter is handy if your query can produce a lot of results.
  • descending

    This boolean parameter indicates that the results should be returned in reverse order.
  • stale

    This boolean parameter controls the tradeoff between performance and freshness of data.
  • debug

    This boolean parameter fetches low-level debugging information from the view engine.
  • streaming

    This boolean parameter indicates whether the view results should be decoded in a streaming manner.
    When enabled, the iterator internally fetches chunks of the response as required.
    As this is less efficient than fetching all results at once, it is disabled by default,
    but can be very useful if you have a large dataset because
    it prevents the entire view from being buffered in memory.
编码与序列化

Python SDK 默认使用 编码格式JSON,使用json标准库

也可以指定使用其他编码格式:

import pprint
from couchbase import Couchbase, FMT_PICKLE
c = Couchbase.connect(bucket='default')
c.set("a_python_object", object(), format=FMT_PICKLE)
c.set("a_python_set", set([1,2,3]), format=FMT_PICKLE)
pprint.pprint(c.get("a_python_object").value)
pprint.pprint(c.get("a_python_set").value)

Output:

<object object at 0x7fa7d0ad80e0>
set([1, 2, 3])

链接

Couchbase III(Python Library)的更多相关文章

  1. Where is the python library installed?

    configure: error: Could not link test program to Python. Maybe the main Python library has been inst ...

  2. Python library not found: libpython2.7mu.so.1.0

    在使用pyinstaller生成python可执行文件的时候,包错误,提示有几个依赖的库找不到:Python library not found: libpython2.7mu.so.1.0 参考st ...

  3. kivy.org - Open source Python library for rapid development of applications

    kivy.org - Open source Python library for rapid development of applicationsthat make use of innovati ...

  4. Scipy - Python library - Math tool - Begin

    Introduction Scientific Computing Tools for Python. Seen in Scipy.org. Environment Linux, CentOS 7 w ...

  5. error: Unable to find vcvarsall.bat while install python library by pip install or python setup.py install.

    Python 2.7 会搜索 Visual Studio 2008. 如果你电脑上没有这个版本的话,比如只有: 1.Visual Studio 2010,在cmd里面执行:SET VS90COMNTO ...

  6. [leetcode]Best Time to Buy and Sell Stock III @ Python

    原题地址:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/ 题意: Say you have an array ...

  7. SimpleCV install and "You need the python image library to save by filehandle"

    2015年5月3日 22:15:43 在win7下安装了python.simplecv,试着运行simplecv官网第一个hello world程序结果报错,提示说%python%/lib/site- ...

  8. Python Standard Library

    Python Standard Library "We'd like to pretend that 'Fredrik' is a role, but even hundreds of vo ...

  9. Libsvm:脚本(subset.py、grid.py、checkdata.py) | MATLAB/OCTAVE interface | Python interface

    1.脚本 This directory includes some useful codes: 1. subset selection tools. (子集抽取工具) subset.py 2. par ...

随机推荐

  1. 模拟 百度之星资格赛 1003 IP聚合

    题目传送门 /* 模拟水题,排序后找出重复的ip就可以了 */ #include <cstdio> #include <iostream> #include <algor ...

  2. Mysql查询语句的 where子句、group by子句、having子句、order by子句、limit子句

    Mysql的各个查询语句 一.where子句   语法:select *|字段列表 from 表名 where 表达式.where子句后面往往配合MySQL运算符一起使用(做条件判断) 作用:通过限定 ...

  3. Android中ProgressBar显示小数的方法

    Android原生的ProgressBar的ProgressDialog.STYLE_HORIZONTAL(即水平样式)默认setMax和setProgress只能传int型的参数,而实际项目中我需要 ...

  4. .net 音频转换 .amr 转 .mp3 (ffmpeg转换法)

    最近看来是跟声音干上了啊! 音频转换的第二种方法,这种方法相对第一种来说,要简单的多! 首先,你得下载个“ffmpeg.exe” 插件,然后把它放到你的项目中,如下图: 程序中会调用该文件,以助于转换 ...

  5. ubuntu安装mysql多实例

    想要尝试mysql的读写分离,在云上安装完mysql之后突然想到一个问题:我本机是没有公网IP的. 开始尝试在唯一一台云服务器上安装多个mysql实例. 主要步骤: 1.新建MySQL目录 (1):新 ...

  6. Haproxy+Rabbitmq中的问题

    问题一.Rabbitmq集群搭建完成 某个集群节宕机后 无法添加失败 解决办法:停掉所有Rabbitmq服务 并删除集群文件C\Users\Administrator\AppData\Roaming\ ...

  7. Handler引起的内存泄露

    一般我都写handler的时候是这样的:   public class MyActivity extends Activity{ private final Handler myHandler = n ...

  8. NSString 与NSMutableString的区别

      NSString 与NSMutableString的区别    Suppose You have a code like this NSString *s = [[NSString alloc]  ...

  9. java实现单向链表的增、删、改、查

    单向链表 作者:vashon package com.ywx.link; /** * 单向链表 * @author vashon * */ public class LinkTest { public ...

  10. win10忘记wifi记录

    1.点击桌面右下角无线图标 2.点击网络设置 3.点击管理WIFI设置 4.点击要管理的账户,忘记或者共享该wifi.