当前位置: 首页 > 工具软件 > CherryPy > 使用案例 >

cherrypy和MySQL连用_如何在Cherrypy和SQLAlchemy的同一请求中使用多个数据库?

弓磊
2023-12-01

# meta.pyimportcherrypyimportsqlalchemyfromsqlalchemyimportMetaDatafromsqlalchemy.ormimportscoped_session,sessionmakerfromsqlalchemy.ext.declarativeimportdeclarative_base# Return an Enginedefcreate_engine(defaultschema=True,schema="",**kwargs):# A blank DB is the same as no DB so to specify a non-schema-specific connection just override with defaultschema = FalseconnectionString='mysql://%s:%s@%s/%s?charset=utf8'%(store['application'].config['main']['database-server-config-username'],store['application'].config['main']['database-server-config-password'],store['application'].config['main']['database-server-config-host'],store['application'].config['main']['database-server-config-defaultschema']ifdefaultschemaelseschema)# Create engine object. we pass **kwargs through so this call can be extendedreturnsqlalchemy.create_engine(connectionString,echo=True,pool_recycle=10,echo_pool=True,encoding='utf-8',**kwargs)# Enginesmain_engine=create_engine()user_engine=None# Sessions_main_session=None_user_session=None# Metadatamain_metadata=MetaData()main_metadata.bind=main_engine

user_metadata=MetaData()# No idea what bases are/do but nothing works without themmain_base=declarative_base(metadata=main_metadata)user_base=declarative_base(metadata=user_metadata)# An easy collection of user database connectionsengines={}# Each thread gets a session based on this objectGlobalSession=scoped_session(sessionmaker(autoflush=True,autocommit=False,expire_on_commit=False))defmain_session():_main_session=cherrypy.request.main_dbsession

_main_session.configure(bind=main_engine)return_main_sessiondefuser_session():_user_session=cherrypy.request.user_dbsession

_user_session.configure(bind=get_user_engine())return_user_sessiondefget_user_engine():# Get dburi from the users instancedburi=cherrypy.session['auth']['user'].instance.database# Store this engine for future useifdburiinengines:engine=engines.get(dburi)else:engine=engines[dburi]=create_engine(defaultschema=False,schema=dburi)# Return Enginereturnenginedefget_user_metadata():user_metadata.bind=get_user_engine()returnuser_metadata# open a new session for the life of the requestdefopen_dbsession():cherrypy.request.user_dbsession=cherrypy.thread_data.scoped_session_class

cherrypy.request.main_dbsession=cherrypy.thread_data.scoped_session_classreturn# close the session for this requestdefclose_dbsession():ifhasattr(cherrypy.request,"user_dbsession"):try:cherrypy.request.user_dbsession.flush()cherrypy.request.user_dbsession.remove()delcherrypy.request.user_dbsessionexcept:passifhasattr(cherrypy.request,"main_dbsession"):try:cherrypy.request.main_dbsession.flush()cherrypy.request.main_dbsession.remove()delcherrypy.request.main_dbsessionexcept:passreturn# initialize the session factory class for the selected threaddefconnect(thread_index):cherrypy.thread_data.scoped_session_class=scoped_session(sessionmaker(autoflush=True,autocommit=False))return# add the hooks to cherrypycherrypy.tools.dbsession_open=cherrypy.Tool('on_start_resource',open_dbsession)cherrypy.tools.dbsession_close=cherrypy.Tool('on_end_resource',close_dbsession)cherrypy.engine.subscribe('start_thread',connect)

 类似资料: