CouchDB and Pyramid

If you want to use CouchDB (via the couchdbkit package) in Pyramid, you can use the following pattern to make your CouchDB database available as a request attribute. This example uses the starter scaffold. (This follows the same pattern as the MongoDB和 Pyramid 例子。)

First add configuration values to your development.ini 文件,包括couchdb uri和数据库名称(couchdb数据库名称可以是任何名称)。

1
2
3
4
 [app:main]
 # ... other settings ...
 couchdb.uri = http://localhost:5984/
 couchdb.db = mydb

然后在你 __init__.py ,设置使数据库附加到每个新请求::

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from pyramid.config import Configurator
from couchdbkit import *


def main(global_config, \**settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = Configurator(settings=settings)
    config.registry.db = Server(uri=settings['couchdb.uri'])

    def add_couchdb(request):
        db = config.registry.db.get_or_create_db(settings['couchdb.db'])
        return db

    config.add_request_method(add_couchdb, 'db', reify=True)

    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('home', '/')
    config.scan()
    return config.make_wsgi_app()

注解

Configurator.add_request_method has been available since Pyramid 1.4. 你可以使用 Configurator.set_request_property for Pyramid 1.3.

此时,在视图代码中,可以使用 request.db as the CouchDB database connection. 例如::

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from pyramid.view import view_config

@view_config(route_name='home', renderer='templates/mytemplate.pt')
def my_view(request):
    """ Get info for server
    """
    return {
        'project': 'pyramid_couchdb_example',
        'info': request.db.info()
    }

Add info to home template:

1
 <p>${info}</p>

CouCHDB视图

First let's create a view for our page data in CouchDB. We will use the ApplicationCreated event and make sure our view containing our page data. For more information on views in CouchDB see Introduction to Views . In __init__.py:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from pyramid.events import subscriber, ApplicationCreated

@subscriber(ApplicationCreated)
def application_created_subscriber(event):
    registry = event.app.registry
    db = registry.db.get_or_create_db(registry.settings['couchdb.db'])

    pages_view_exists = db.doc_exist('lists/pages')
    if pages_view_exists == False:
        design_doc = {
            '_id': '_design/lists',
            'language': 'javascript',
            'views': {
                'pages': {
                    'map': '''
                        function(doc) {
                            if (doc.doc_type === 'Page') {
                                emit([doc.page, doc._id], null)
                            }
                        }
                    '''
                }
            }
        }
        db.save_doc(design_doc)

CouchDB Documents

现在,我们可以在视图代码中的couchdb文档的主页文档中添加一些数据(如果不存在)::

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import datetime

from couchdbkit import *

class Page(Document):
    author = StringProperty()
    page = StringProperty()
    content = StringProperty()
    date = DateTimeProperty()

@view_config(route_name='home', renderer='templates/mytemplate.pt')
def my_view(request):

    def get_data():
        return list(request.db.view('lists/pages', startkey=['home'], \
                endkey=['home', {}], include_docs=True))

    page_data = get_data()

    if not page_data:
        Page.set_db(request.db)
        home = Page(
            author='Wendall',
            content='Using CouchDB via couchdbkit!',
            page='home',
            date=datetime.datetime.utcnow()
        )
        # save page data
        home.save()
        page_data = get_data()

    doc = page_data[0].get('doc')

    return {
        'project': 'pyramid_couchdb_example',
        'info': request.db.info(),
        'author': doc.get('author'),
        'content': doc.get('content'),
        'date': doc.get('date')
    }

然后再次更新主模板以添加自定义值:

1
2
3
4
5
 <p>
     ${author}<br />
     ${content}<br />
     ${date}<br />
 </p>