我正在尝试使用_users
从数据库couchdb-python
存储和检索用户。我是couchdb
的初学者。
我使用couchdb文档couchdb.mapping.Document
映射了python类User,如下所示:
import couchdb.mapping as cmap
class User(cmap.Document):
name = cmap.TextField()
password = cmap.TextField()
type = 'user'
roles = {}
但这不起作用。我得到了doc.type must be user
ServerError
所以可能我声明类型不正确的方式。
我应该如何构建我的类以与_users
数据库一起使用?
答案 0 :(得分:0)
在IRC的#couchdb
频道提供一些提示后,我出来了这个课程(这可能比我要求的要多......)
import couchdb.mapping as cmap
class User(cmap.Document):
""" Class used to map a user document inside the '_users' database to a
Python object.
For better understanding check https://wiki.apache.org
/couchdb/Security_Features_Overview
Args:
name: Name of the user
password: password of the user in plain text
type: (Must be) 'user'
roles: Roles for the users
"""
def __init__(self, **values):
# For user in the _users database id must be org.couchdb.user:<name>
# Here we're auto-generating it.
if 'name' in values:
_id = 'org.couchdb.user:{}'.format(values['name'])
cmap.Document.__init__(self, id=_id, **values)
type = cmap.TextField(default='user')
name = cmap.TextField()
password = cmap.TextField()
roles = cmap.ListField(cmap.TextField())
@cmap.ViewField.define('users')
def default(doc):
if doc['name']:
yield doc['name'], doc
这应该有效:
db = couchdb.server()['_users']
alice = User(name="Alice", password="strongpassword")
alice.store(db)