MongoDB和 Pyramid

基础

如果您想通过Pyramid使用MangGDB(通过PyMongo和GRIDFS),您可以使用以下模式使您的Mango数据库作为请求属性可用。

First add the MongoDB URI to your development.ini 文件。(注: userpasswordport are not required.)

1
2
3
 [app:myapp]
 # ... other settings ...
 mongo_uri = mongodb://user:password@host:port/database

然后在你 __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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from pyramid.config import Configurator

try:
    # for python 2
    from urlparse import urlparse
except ImportError:
    # for python 3
    from urllib.parse import urlparse

from gridfs import GridFS
from pymongo import MongoClient


def main(global_config, **settings):
   """ This function returns a Pyramid WSGI application.
   """
   config = Configurator(settings=settings)
   config.add_static_view('static', 'static', cache_max_age=3600)

   db_url = urlparse(settings['mongo_uri'])
   config.registry.db = MongoClient(
       host=db_url.hostname,
       port=db_url.port,
   )

   def add_db(request):
       db = config.registry.db[db_url.path[1:]]
       if db_url.username and db_url.password:
           db.authenticate(db_url.username, db_url.password)
       return db

   def add_fs(request):
       return GridFS(request.db)

   config.add_request_method(add_db, 'db', reify=True)
   config.add_request_method(add_fs, 'fs', reify=True)

   config.add_route('dashboard', '/')
   # other routes and more config...
   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 作为PyMongo数据库连接。例如::

1
2
3
4
5
@view_config(route_name='dashboard',
             renderer="myapp:templates/dashboard.pt")
def dashboard(request):
    vendors = request.db['vendors'].find()
    return {'vendors':vendors}

脚手架

Niall O'Higgins提供了 pyramid_mongodb Pyramid 的脚手架,提供了一个简单的方法开始 Pyramid 和MongoDB。

视频

尼尔-奥希金斯在旧金山Mongo会议上发表了一个演讲。