Pylons 經過漫長的開發,終于放出了 1.0 版本。對于正規的產品開發來說,1.0 版本的意義很大,這表明 Pylons 的 API 終于穩定下來了。
Pylons 雖是山寨 Rails 而生,但作為一個純 Python 的 Web 框架,它有一個鮮明的特點:可定制性強??蚣苊恳粚佣紱]重新發明輪子,而是盡量整合現有的 Python 庫。在 MVC 的 Model 層,Pylons 默認支持 SQLAlchemy?,F在 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 中加入
新聞熱點
疑難解答