在 Pylons 中使用 MongoDB 的例子
Pylons 经过漫长的开发,最近终于 Release 了 1.0 版本,对于正规的 Production 开发来说,1.0 版本的意义很大,这表明 Pylons 的 API 终于稳定下来了。
Pylons 虽然算是由“山寨” Rails 而生,但作为一个纯 Python 的 Web Framework,它有一个鲜明的特点:可定制性强。Framework 的每一层都是采用了现成的 Python 库,而且每一层都可以自由替换。在 MVC 的 Model 层,Pylons 默认支持 SQLAlchemy 这个 RDB ORM Framework。现在 NoSQL 很火,MongoDB 是众多 NoSQL DB 里比较热门的一个。在 Pylons 的 Model 层应用 MongoDB 也比较简单,可惜网上没有现成的例子,下面就是自己研究代码,做的一个简单的例子。
PROJECT/model/__init__.py 中加入 MongoDB 初始化函数和程序所需的实体定义:
from ming import Session from ming import schema from ming.orm import MappedClass from ming.orm import FieldProperty, ForeignIdProperty, RelationProperty from ming.orm import ThreadLocalORMSession session = None def init_single_model(model_class): model_class.__mongometa__.session = session class Page(MappedClass): class __mongometa__: session = session name = 'pages' _id = FieldProperty(schema.ObjectId) title = FieldProperty(str) content = FieldProperty(str) def init_model(engine): global session session = ThreadLocalORMSession(doc_session=Session(engine)) init_single_model(Page) MappedClass.compile_all() |
PROJECT/config/environment.py 中加入初始化动作:
... from ..model import init_model from ming.datastore import DataStore def load_environment(global_conf, app_conf): ... # Create the Mako TemplateLookup, with the default auto-escaping config['pylons.app_globals'].mako_lookup = TemplateLookup( directories=paths['templates'], error_handler=handle_mako_error, module_directory=os.path.join(app_conf['cache_dir'], 'templates'), input_encoding='utf-8', default_filters=['escape'], imports=['from webhelpers.html import escape']) # Setup the mongodb database engine init_model(DataStore(config['database.uri'])) # CONFIGURATION OPTIONS HERE (note: all config options will override # any Pylons config options) return config |
最后在 development.ini 中加入 MongoDB 的配置项:
... [app:main] database.uri = mongodb://localhost:27017/test ... |
另外还可以在程序安装时初始化数据库, 在 PROJECT/websetup.py 中加入:
"""Setup the wukong application""" import logging import pylons.test from .config.environment import load_environment from . import model log = logging.getLogger(__name__) def setup_app(command, conf, vars): """Place any commands to setup wukong here""" # Don't reload the app if it was loaded under the testing environment if not pylons.test.pylonsapp: load_environment(conf.global_conf, conf.local_conf) log.info("Adding demo data.") page = model.Page(title='demo', content='This is for demo.') model.session.flush() log.info("Successfully set up.") |
这里使用了 Ming 库来连接 MongoDB 并做简单的 ORM。最近 SourceForge 改用 turbogears + MongoDB 进行重构时,改写者将项目中对 PyMongo 的封装开源为 Ming 库,使用起来有点 SQLAlchemy ORM 的感觉。当然,上面的例子做简单的修改就可以把 Ming 替换成 MongoKit 或其它 MongoDB 的 Python 库,甚至直接用 PyMongo 也无不可。
有种感觉,MongoDB 会火。
文章信息
- 原创文章,转载请注明:转载自 道可道 | 在 Pylons 中使用 MongoDB 的例子 http://zhuoqiang.me/a/use-mongodb-in-pylons
- 版权声明 License:自由转载-非商用-非衍生-保持署名 | Creative Commons BY-NC-ND 3.0

你好,
现在Ming已经更改了API,你的这个demo怕是已经不能工作了。。。
我的博客里有一篇参照您的文章给出的detailed demo, 也不能用了。。。
很久不关注 Ming 了,不止是 Ming 变了,Pylons 也进化成了 Pyramid 。
最近用 Mongodb 都是直接上 pymongo。MongoDB 太灵活了,往上硬套 ORM 会束手束脚。当然,有时必须给“孙猴子安上紧箍咒”