Python Web框架Pylons中使用MongoDB的例子
pylons 经过漫长的开发,终于放出了 1.0 版本。对于正规的产品开发来说,1.0 版本的意义很大,这表明 pylons 的 api 终于稳定下来了。
pylons 虽是山寨 rails 而生,但作为一个纯 python 的 web 框架,它有一个鲜明的特点:可定制性强。框架每一层都没重新发明*,而是尽量整合现有的 python 库。在 mvc 的 model 层,pylons 默认支持 sqlalchemy。现在 nosql 很火 mongodb 很热。在 pylons 中应用 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。ming 库是对 pymongo 的 orm 包装库。它是 sourceforge 用 turbogears 和 mongodb 对网站进行重构的副产物。使用起来有点象 sqlalchemy orm 。在上面的示例中,也可以把 ming 替换成 mongokit 或其它 mongodb 的 orm 库,甚至直接用 pymongo 也无不可。
有种感觉,mongodb 会火。
推荐阅读