3

_usersを使用してデータベースからユーザーを保存および取得しようとしていますcouchdb-python。私は の初心者です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データベースで使用するクラスをどのように作成すればよいですか?

4

1 に答える 1

2

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)
于 2016-03-29T14:12:25.460 に答える