我正在尝试使用 couchdb-python
从数据库 _users
中存储和检索用户。我是 couchdb
的初学者。
我将 python 类 User 映射到 couchdb Document couchdb.mapping.Document
,如下所示:
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
数据库一起使用?
最佳答案
在 IRC 上的 #couchdb
channel 的一些提示之后,我提出了这个类(class)(这可能比我问的要多......)
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)
关于python - 使用 couchdb-python 管理 _users 中的用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35941497/