MongoDB and Pyramid¶
Basics¶
If you want to use MongoDB (via PyMongo and perhaps GridFS) via Pyramid, you can use the following pattern to make your Mongo database available as a request attribute.
First add the MongoDB URI to your development.ini
file. (Note: user
, password
and port
are not required.)
1 [app:myapp]
2 # ... other settings ...
3 mongo_uri = mongodb://user:password@host:port/database
Then in your __init__.py
, set things up such that the database is
attached to each new request:
1from pyramid.config import Configurator
2
3try:
4 # for python 2
5 from urlparse import urlparse
6except ImportError:
7 # for python 3
8 from urllib.parse import urlparse
9
10from gridfs import GridFS
11from pymongo import MongoClient
12
13
14def main(global_config, **settings):
15 """ This function returns a Pyramid WSGI application.
16 """
17 config = Configurator(settings=settings)
18 config.add_static_view('static', 'static', cache_max_age=3600)
19
20 db_url = urlparse(settings['mongo_uri'])
21 config.registry.db = MongoClient(
22 host=db_url.hostname,
23 port=db_url.port,
24 )
25
26 def add_db(request):
27 db = config.registry.db[db_url.path[1:]]
28 if db_url.username and db_url.password:
29 db.authenticate(db_url.username, db_url.password)
30 return db
31
32 def add_fs(request):
33 return GridFS(request.db)
34
35 config.add_request_method(add_db, 'db', reify=True)
36 config.add_request_method(add_fs, 'fs', reify=True)
37
38 config.add_route('dashboard', '/')
39 # other routes and more config...
40 config.scan()
41 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 PyMongo database
connection. For example:
1@view_config(route_name='dashboard',
2 renderer="myapp:templates/dashboard.pt")
3def dashboard(request):
4 vendors = request.db['vendors'].find()
5 return {'vendors':vendors}
Scaffolds¶
Niall O'Higgins provides a pyramid_mongodb scaffold for Pyramid that provides an easy way to get started with Pyramid and MongoDB.
Video¶
Niall O'Higgins provides a presentation he gave at a Mongo conference in San Francisco at https://www.mongodb.com/presentations/weather-century
Other Information¶
Pyramid, Aket and MongoDB: http://niallohiggins.com/2011/05/18/mongodb-python-pyramid-akhet/