Posted on 2009-01-27 14:00
laogao 阅读(1180)
评论(0) 编辑 收藏 所属分类:
On Python
在前面的4篇随笔中,我们简要的介绍了SQLAlchemy,不过SQLAlchemy如何被集成到Pylons应用中呢?
首先我们看一下自动生成代码中的model子目录,其中有两个文件__init__.py和meta.py,其中meta.py定义了engine、Session和metadata三个公用变量,而__init__.py提供了一个核心的init_model(engine)方法,该方法分别将数据库engine和经过sessionmaker和scoped_session包装的Session对象植入到meta中,像这样:
sm = orm.sessionmaker(autoflush=True, autocommit=True, bind=engine)
meta.engine = engine
meta.Session = orm.scoped_session(sm)
这样一来,整个背后的"magic"就还剩下最后一块"拼图":谁来把engine初始化好并调用init_model方法呢?看看config/environment.py就清楚了:
1 """Pylons environment configuration"""
2 import os
3
4 from mako.lookup import TemplateLookup
5 from pylons.error import handle_mako_error
6 from pylons import config
7 from sqlalchemy import engine_from_config
8
9 import newapp.lib.app_globals as app_globals
10 import newapp.lib.helpers
11 from newapp.config.routing import make_map
12 from newapp.model import init_model
13
14 def load_environment(global_conf, app_conf):
15 """Configure the Pylons environment via the ``pylons.config``
16 object
17 """
18 # Pylons paths
19 root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
20 paths = dict(root=root,
21 controllers=os.path.join(root, 'controllers'),
22 static_files=os.path.join(root, 'public'),
23 templates=[os.path.join(root, 'templates')])
24
25 # Initialize config with the basic options
26 config.init_app(global_conf, app_conf, package='newapp', paths=paths)
27
28 config['routes.map'] = make_map()
29 config['pylons.app_globals'] = app_globals.Globals()
30 config['pylons.h'] = newapp.lib.helpers
31
32 # Create the Mako TemplateLookup, with the default auto-escaping
33 config['pylons.app_globals'].mako_lookup = TemplateLookup(
34 directories=paths['templates'],
35 error_handler=handle_mako_error,
36 module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
37 input_encoding='utf-8', output_encoding='utf-8',
38 imports=['from webhelpers.html import escape'],
39 default_filters=['escape'])
40
41 # Setup SQLAlchemy database engine
42 engine = engine_from_config(config, 'sqlalchemy.')
43 init_model(engine)
44
45 # CONFIGURATION OPTIONS HERE (note: all config options will override
46 # any Pylons config options)
注意第7行的import和第42、43行代码,是不是豁然开朗?Pylons在初始化运行环境时,从config中读取sqlalchemy相关的配置信息,然后通过这些配置信息创建数据库engine,并调用init_model()方法初始化SQLAlchemy功能的核心对象:metadata和Session。有了meta.Session,我们就可以方便的在代码中执行对model层/数据库的访问了。