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 [app:main]
2 # ... other settings ...
3 couchdb.uri = http://localhost:5984/
4 couchdb.db = mydb

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

 1from pyramid.config import Configurator
 2from couchdbkit import *
 3
 4
 5def main(global_config, \**settings):
 6    """ This function returns a Pyramid WSGI application.
 7    """
 8    config = Configurator(settings=settings)
 9    config.registry.db = Server(uri=settings['couchdb.uri'])
10
11    def add_couchdb(request):
12        db = config.registry.db.get_or_create_db(settings['couchdb.db'])
13        return db
14
15    config.add_request_method(add_couchdb, 'db', reify=True)
16
17    config.add_static_view('static', 'static', cache_max_age=3600)
18    config.add_route('home', '/')
19    config.scan()
20    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. 例如::

 1from pyramid.view import view_config
 2
 3@view_config(route_name='home', renderer='templates/mytemplate.pt')
 4def my_view(request):
 5    """ Get info for server
 6    """
 7    return {
 8        'project': 'pyramid_couchdb_example',
 9        'info': request.db.info()
10    }

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:

 1from pyramid.events import subscriber, ApplicationCreated
 2
 3@subscriber(ApplicationCreated)
 4def application_created_subscriber(event):
 5    registry = event.app.registry
 6    db = registry.db.get_or_create_db(registry.settings['couchdb.db'])
 7
 8    pages_view_exists = db.doc_exist('lists/pages')
 9    if pages_view_exists == False:
10        design_doc = {
11            '_id': '_design/lists',
12            'language': 'javascript',
13            'views': {
14                'pages': {
15                    'map': '''
16                        function(doc) {
17                            if (doc.doc_type === 'Page') {
18                                emit([doc.page, doc._id], null)
19                            }
20                        }
21                    '''
22                }
23            }
24        }
25        db.save_doc(design_doc)

CouchDB Documents

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

 1import datetime
 2
 3from couchdbkit import *
 4
 5class Page(Document):
 6    author = StringProperty()
 7    page = StringProperty()
 8    content = StringProperty()
 9    date = DateTimeProperty()
10
11@view_config(route_name='home', renderer='templates/mytemplate.pt')
12def my_view(request):
13
14    def get_data():
15        return list(request.db.view('lists/pages', startkey=['home'], \
16                endkey=['home', {}], include_docs=True))
17
18    page_data = get_data()
19
20    if not page_data:
21        Page.set_db(request.db)
22        home = Page(
23            author='Wendall',
24            content='Using CouchDB via couchdbkit!',
25            page='home',
26            date=datetime.datetime.utcnow()
27        )
28        # save page data
29        home.save()
30        page_data = get_data()
31
32    doc = page_data[0].get('doc')
33
34    return {
35        'project': 'pyramid_couchdb_example',
36        'info': request.db.info(),
37        'author': doc.get('author'),
38        'content': doc.get('content'),
39        'date': doc.get('date')
40    }

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

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