我刚刚发现我的 Pyramid 应用程序存在一个非常大的问题。mongo 脚手架暗示事件处理程序也应该用于处理数据库连接。这个想法是,当新请求进来时,连接到数据库,当页面呈现断开连接时。所以这就是我所做的,在我的__init.py__
def connectDatabase(event):
mongo = MongoDB()
con = mongo.connectDatabase()
db = con[Cfg_MongoDB_Database]
event.request.con = con
event.request.db = db
redis = Redis()
con = redis.connectDatabase()
event.request.redis = con
log.debug('newrequest')
def closeConnection(event):
mongo = MongoDB()
mongo.closeConnection(event.request.con)
log.debug('newresponse')
def main(global_config, **settings):
config = Configurator(settings=settings, root_factory=Dashboard)
authentication = AuthTktAuthenticationPolicy(Cfg_Auth_Key, hashalg='sha512',\
include_ip=False, timeout=3600*24*7, max_age=3600*24*7, reissue_time=3600)
authorization = ACLAuthorizationPolicy()
config.set_authentication_policy(authentication)
config.set_authorization_policy(authorization)
config.add_static_view('includes', 'includes', cache_max_age=3600)
config.add_renderer(".html", "pyramid.mako_templating.renderer_factory")
config.add_route('dash', '/')
config.add_subscriber(connectDatabase, NewRequest)
config.add_subscriber(closeConnection, NewResponse)
log.debug('main')
config.scan()
return config.make_wsgi_app()
但是,我将一些记录器放入连接到数据库的方法中,并发现该方法被调用了 10 多次,并且如果我禁用缓存add_static_view
超过 100 次。这意味着对于每个 css、image、js,都会建立新的连接。这是巨大的开销!该站点需要 300ms 连接数据库 100 次!
/Users/jan/Documents/Test2/test2/data.py changed; reloading...
-------------------- Restarting --------------------
2013-02-01 18:32:48,351 DEBUG [test2.tools][MainThread] main
Starting server in PID 12374.
serving on http://127.0.0.1:6543
2013-02-01 18:34:14,451 DEBUG [test2.tools][Dummy-2] newrequest
2013-02-01 18:34:14,582 DEBUG [test2.tools][Dummy-2] newresponse
2013-02-01 18:34:14,952 DEBUG [test2.tools][Dummy-3] newrequest
2013-02-01 18:34:14,953 DEBUG [test2.tools][Dummy-3] newresponse
2013-02-01 18:34:17,459 DEBUG [test2.tools][Dummy-4] newrequest
2013-02-01 18:34:17,474 DEBUG [test2.tools][Dummy-4] newresponse
2013-02-01 18:34:17,482 DEBUG [test2.tools][Dummy-5] newrequest
2013-02-01 18:34:17,497 DEBUG [test2.tools][Dummy-5] newresponse
2013-02-01 18:34:19,158 DEBUG [test2.tools][Dummy-2] newrequest
2013-02-01 18:34:19,159 DEBUG [test2.tools][Dummy-2] newresponse
所以到目前为止的解决方案是将连接移动到模型。但是我怎么知道什么时候可以关闭连接?有人对我的问题有更好、更优雅的解决方案吗?