焦基
pycouchbase的Python项目详细描述
为什么要在sdk中添加另一层呢?
- couchbase文档中不一致的数据类型可能是一个真正的难题。
- 更好地管理多个couchbase连接。
- 在python源代码中couchbase文档的可读性,同时仍然能够使用couchbase sdk的操作。
功能
- 它最初是由couchbasekit派生出来的,并受到了couchbasekit的启发。
- 验证couchbase文档。
- 将couchbase文档表示为python对象。
- 轻松管理多个CouchBase连接。
- 支持Couchbase Python SDK 2.0操作。
- couchbasekit中已经包含了一些数据检索操作,但是我还没有用pycouchbase对其进行彻底的测试。
安装
在命令行:
$ easy_install pycouchbase
或者,如果安装了virtualenvwrapper:
$ mkvirtualenv pycouchbase $ pip install pycouchbase
开始
让我们举一个简单的例子。
导入我们需要的所有内容:
importdatetimefrompycouchbaseimportConnectionfrompycouchbaseimportDocument,register_viewfrompycouchbase.fieldsimportEmailField,ChoiceField
声明文档类:
# You can define your own field/data typeclassGender(ChoiceField):CHOICES={'M':'Male','F':'Female',}@register_view('dev_authors')classAuthor(Document):__bucket_name__='couchbasekit_samples'__key_field__='slug'# optionaldoc_type='author'structure={'slug':unicode,'first_name':unicode,'last_name':unicode,'gender':Gender,'email':EmailField,'has_book':bool,'age':int,'birthday':datetime.date,'created_at':datetime.datetime,}default_values={# optional'has_book':False,# don't worry about the timezone info!# it's auto assigned as to UTC, so all you have to do is:'created_at':datetime.datetime.utcnow,}required_fields=(# optional'slug','first_name','last_name','email',)
验证并保存文档:
local_connection=Connection.auth(server='localhost')author=Author()bucket=author.get_bucket(local_connection)author.update({'slug':u'douglas_adams','first_name':u'Douglas','last_name':u'Adams','gender':Gender('M'),'email':EmailField('dna@example.com'),})# Try to validate before savingtry:author.validate()try:rvs=bucket.insert(author.slug,author.encode())exceptKeyExistsErroraswhy:print(why)exceptAuthor.StructureErroraswhy:# when the data structure is invalidprint(why)
保存多个文档:
local_connection=Connection.auth(server='localhost')author=Author()list_data=[{'slug':u'douglas_adams','first_name':u'Douglas','last_name':u'Adams','gender':Gender('M'),'email':EmailField('dna@example.com'),},{'slug':u'isaac_asimov','first_name':u'Isaac','last_name':u'Asimov','gender':Gender('M'),'email':EmailField('dna@example.com'),}]try:bucket=author.get_bucket(local_connection)updated_authors={}fordinlist_data:author.update(d)try:# validate!author.validate()updated_authors.update({d['slug']:author.encode()})exceptauthor.StructureErroraswhy:print(why)# save multiple datarvs=bucket.upsert_multi(updated_authors)exceptCouchbaseNetworkErroraswhy:print(why)
管理多个连接:
connection_1=Connection.auth(server='server_1')connection_2=Connection.auth(server='server_2')# where doc_1 and doc_2 are document objectsbucket_1=doc_1.get_bucket(connection_1)bucket_2=doc_2.get_bucket(connection_2)
bucket对象可以支持任何Couchbase Python SDK 2.0操作:
bucket_1.get('key_or_id')bucket_1.insert('key_or_id',value)
有关couchbase sdk支持的操作的详细信息,请参见:http://docs.couchbase.com/developer/python-2.0/introduction.html
历史记录
0.1.0(2015-01-11)
- pypi上的第一个版本。