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. DataGridView 绑定List<>数据的更新

    使用BindingSource做为中间数据源,使用 bindingSource1.DataSource = productOrderList;dataGridView1.DataSource = bi ...

  2. [已读]HTML5与CSS3设计模式

    我想说,不要被书名骗了,其实并没有涉及丁点h5与css3的内容,但是确实称得上比较详细的一本关于css的书.看它的页数就知道了,481~~ 今年上半年看完的,现在想想,觉得自己还是蛮拼的.内容会比较枯 ...

  3. WebStorm 10.0.3注册码

    UserName:William ===== LICENSE BEGIN ===== 45550-12042010 00001SzFN0n1bPII7FnAxnt0DDOPJA INauvJkeVJB ...

  4. 【转】Java泛型方法

    1. 定义泛型方法 (1) 如果你定义了一个泛型(类.接口),那么Java规定,你不能在所有的静态方法.静态初块等所有静态内容中使用泛型的类型参数.例如: public class A<T> ...

  5. 【学习笔记】比特(bit)、字,字节(B)存储单位之间的关系+其与操作系统位数的关系+不同编译器编译方式下数据类型的表示范围

    1.在表示网络传输速度中与表示存储单位的不同: 表示存储单位时:1kB=1024B,但在网络中表示传输速度是1KB=1000B 2.下面介绍表示存储单位时的关系及其与操作系统位数的关系: 1B=8bi ...

  6. RxJava尝试取代Handler初探

    在之前的一篇文章中,我们探究了RxJava的使用方法,详细请看https://www.cnblogs.com/yanyojun/p/9745675.html 根据扔物线大神的描述,如果用一个词来概括R ...

  7. Java Web MVC实例

    开发环境 Eclipse Java EE IDE for Web Developers. Version: Luna Service Release 2 (4.4.2) tomcat:7.0 数据库: ...

  8. (转)编码剖析Spring管理Bean的原理

    http://blog.csdn.net/yerenyuan_pku/article/details/52832434 在Spring的第一个案例中,我们已经知道了怎么将bean交给Spring容器进 ...

  9. Android(java)学习笔记177: 服务(service)之音乐播放器

    1.我们播放音乐,希望在后台长期运行,不希望因为内存不足等等原因,从而导致被gc回收,音乐播放终止,所以我们这里使用服务Service创建一个音乐播放器. 2.创建一个音乐播放器项目(使用服务) (1 ...

  10. 1-1 编程基础 GCC程序编译

    GCC简介      Linux系统下的gcc是GNU推出的强大.性能优越的多平台编译器,是GNU的代表作之一.gcc可以在多种硬体平台上编译出可执行程序,其执行效率与一般的编译器相比平局效率要高20 ...