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 and Pyramid example.)
First add configuration values to your development.ini
file, including your
CouchDB URI and a database name (the CouchDB database name, can be anything).
1 [app:main]
2 # ... other settings ...
3 couchdb.uri = http://localhost:5984/
4 couchdb.db = mydb
Then in your __init__.py
, set things up such that the database is
attached to each new request:
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.
You can use Configurator.set_request_property
for Pyramid 1.3.
At this point, in view code, you can use request.db
as the CouchDB database
connection. For example:
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 Views¶
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¶
Now we can let's add some data to a document for our home page in a CouchDB document in our view code if it doesn't exist:
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 }
Then update your home template again to add your custom values:
1 <p>
2 ${author}<br />
3 ${content}<br />
4 ${date}<br />
5 </p>