塔架:与外部库共享SQLAlchemy MySQL连接 [英] Pylons: Sharing SQLAlchemy MySQL connection with external library
问题描述
我正在使用SQLAlchemy运行Pylons以连接到MySQL,因此,当我想在控制器中使用数据库连接时,可以这样做:
I am running Pylons using SQLAlchemy to connect to MySQL, so when I want to use a database connection in a controller, I can do this:
from myapp.model.meta import Session
class SomeController(BaseController):
def index(self):
conn = Session.connection()
rows = conn.execute('SELECT whatever')
...
说我的控制器需要调用一个外部库,它也需要一个数据库连接,我想从已经建立的SQLAlchemy MySQL连接为其提供连接:
Say my controller needs to call up an external library, that also needs a database connection, and I want to provide the connection for it from the SQLAlchemy MySQL connection that is already established:
from myapp.model.meta import Session
import mymodule
class SomeController(BaseController):
def index(self):
conn = Session.connection()
myobject = mymodule.someobject(DATABASE_OBJECT)
...
conn.close()
DATABSE_OBJECT应该是什么?可能性:
What should DATABSE_OBJECT be? Possibilities:
- 传递
Session
-然后在模块代码中打开和关闭Session.connection()
- 传递
conn
,然后在控制器中调用conn.close()
- 只需传递连接参数,并让模块代码设置其自己的连接
- Pass
Session
-- and then open and closeSession.connection()
in the module code - Pass
conn
, and then callconn.close()
in the controller - Just pass the connection parameters, and have the module code set up its own connection
还有一个难题,那就是我需要实例化app_globals.py
中的某些对象,并且这些对象也需要数据库连接.似乎app_globals.py
尚不能使用Session
的SQLAlchemy连接-尚未绑定.
There is another wrinkle, which is that I need to instantiate some objects in app_globals.py
, and these objects need a database connection as well. It seems that app_globals.py
cannot use Session
's SQLAlchemy connection yet -- it's not bound yet.
我的体系结构从根本上是不完善的吗?我是否应该尝试以这种方式在Pylons和外部库之间共享连接?谢谢!
Is my architecture fundamentally unsounds? Should I not be trying to share connections between Pylons and external libraries this way? Thanks!
推荐答案
您不应该自己管理连接-一切都由SQLAlchemy完成.只需在任何地方使用作用域会话对象,就可以了.
You should not manage connections yourself - it's all done by SQLAlchemy. Just use scoped session object everywhere, and you will be fine.
def init_model(engine):
sm = orm.sessionmaker(autoflush=False, autocommit=False, expire_on_commit=False, bind=engine)
meta.engine = engine
meta.Session = orm.scoped_session(sm)
def index(self):
rows = Session.execute('SELECT ...')
您可以将Session对象传递到您的外部库,并根据需要在其中进行查询.无需在其上调用.close().
You can pass Session object to your external library and do queries there as you wish. There is no need to call .close() on it.
关于app_globals,我通过在globals类中添加其他方法解决了这一问题,该方法是从environment.py初始化数据库后调用的
Regarding app_globals, I solved that by adding other method in globals class which is called after db initialization from environment.py
class Globals(...):
def init_model(self, config):
self.some_persistent_db_object = Session.execute('...')
def load_environment(...):
...
config['pylons.app_globals'].init_model(config)
return config
这篇关于塔架:与外部库共享SQLAlchemy MySQL连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!