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. python计算代码运行时间的装饰器

    import time def cal_time(func): def wrapper(*args, **kwargs): t1 = time.time() result = func(*args, ...

  2. vmware虚拟机启动centOs黑屏

    如图所示  , 我的VM 启动虚拟机之后就变成了上面的样子,一直不动,ping也ping不好,这个时候 : 1. 要么 内存不够了: 2. 要么 网络协议存在问题了: 本地windows环境在管理员的 ...

  3. Python: How to iterate list in reverse order

    #1 for index, val in enumerate(reversed(list)): print len(list) - index - 1, val #2 def reverse_enum ...

  4. 1051 - Good or Bad DFS 记忆化搜索

    http://lightoj.com/volume_showproblem.php?problem=1051 对于每个位置,设dfs(cur, one, two)表示前i个字母,拥有辅音字母one个, ...

  5. python工具之日志记录

    ''' 写日志类 日志存放目录为当前应用程序的目录下的log目录中 日志产生规则:每小时产生一个文件 write by :wujf 2017-02-24 ''' import sys import o ...

  6. Java-学完一个月总结(javaSe学习路线)

    JavaSe的一个月 第一周 0410 基本数据类型:数据类型的转换:运算符:导入删除项目0411 分支结构if else:switch case ;while0412 do while ;for / ...

  7. mysql5.7.25集群部署和方案设计(附PXC一键部署脚本)

    还记得我们之前部署mysql集群有多麻烦嘛?波哥来救你们啦!~ 我已将项目上传到了我的github仓库中,大家可以点击仓库地址出现的连接登录查看相应的代码!如果觉得不错别忘了转发.点赞哦! 部署步骤: ...

  8. Delphi定时器控件TTimer“一睡不醒”问题研究

    1,试验1—基础代码 1.1页面控件与代码 定时器 Timer1 Timer_work Interval 1000 1500 Enabled True True Ontimer事件 then exit ...

  9. ios项目中引用其他开源项目

    1. 将开源项目的.xcodeproj拖入项目frameworks 2. Build Phases下 Links Binary With Libraries 引入.a文件.Target Depende ...

  10. nginx 访问localhost老是下载文件不能打开网页什么情况?

    nginx打开网页直接下载文件的问题 nginx sites-available文件里的default已经修改过root 路径了. 但是访问localhost的时候总是直接下载网页而不是打开网址 很奇 ...