在前面的4篇隨筆中,我們簡要的介紹了SQLAlchemy,不過SQLAlchemy如何被集成到Pylons應用中呢?
首先我們看一下自動生成代碼中的model子目錄,其中有兩個文件__init__.py和meta.py,其中meta.py定義了engine、Session和metadata三個公用變量,而__init__.py提供了一個核心的init_model(engine)方法,該方法分別將數(shù)據(jù)庫engine和經(jīng)過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在初始化運行環(huán)境時,從config中讀取sqlalchemy相關的配置信息,然后通過這些配置信息創(chuàng)建數(shù)據(jù)庫engine,并調用init_model()方法初始化SQLAlchemy功能的核心對象:metadata和Session。有了meta.Session,我們就可以方便的在代碼中執(zhí)行對model層/數(shù)據(jù)庫的訪問了。