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. Tomcat启动后打开页面提示404错误的解决

    Eclipse配置并启动Tomcat成功,但有时会访问localhost:8080出现404错误,此时需要修改Tomcat配置.步骤如下: 在Eclipse中双击Tomcat server,打开Tom ...

  2. Reference for shell scripting

    ${var} 和 $var的区别 http://stackoverflow.com/questions/8748831/when-do-we-need-curly-braces-in-variable ...

  3. 162 Find Peak Element 寻找峰值

    峰值元素是指其值大于左右相邻值的元素.给定一个输入数组,其中 num[i] ≠ num[i+1],找到峰值元素并返回其索引.数组可能包含多个峰值,在这种情况下,返回到任何一个峰值所在位置都可以.你可以 ...

  4. GCC KEIL ARM编译器

    经常用keil,也听说IAR的编译效率很高,原来C51时用proteus,最近proteus8开始支持stm32,所以在研究用keil5+HAL+proteus学习STM32F. 问题:因为prote ...

  5. SQL 多字段去重

    select articleID from (select aeUID, max(articleID) articleID from [article] group by aeUID) a conca ...

  6. mybatis generator 整合lombok

    <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration ...

  7. chrome inspect出现白屏的解决方案

    点inspect后 弹出框,可是里面一片白色 PS:原效果不是这样,只是图找不到随便p的 原因可以看这个:http://www.cnblogs.com/slmk/p/7591126.html 大概意思 ...

  8. 8.2.6 PEB —— PEB结构值不正确的问题

    书中作者使用 dt _PEB xxxxxx 命令来查看当前进程的PEB结构. 实际操作后PEB结构显示的成员值: 作为进程链表的LDR结构居然没有值,这显然是不正常的,地址也没有输错,问题到底出在哪里 ...

  9. 错误消息 This computer doesn't have VT-X/AMD-v enabled

    在VirtualBox的Ubuntu虚拟机里试图本地安装Kyma(一个基于Kubernetes的开源框架)时,遇到下面的错误信息: E0827 11:19:38.972489 3093 start.g ...

  10. 聊天室(C++客户端+Pyhton服务器)_1.框架搭设

    聊天室 一.客户端发送 用MFC可视化做个客户端登录界面. 先点击注册账号按钮,注册账号的时候就需要连接到服务器, 服务器需要查数据库,并做出相应的回应. 所以开始写C++客户端套接口类用来连接到服务 ...