我正在为一家公司工作,该项目似乎可以使用单个全局会话变量:
/src/__init__.py
(程序的入口点):
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine('mysql://%s:%s@%s/%s' % (username, password, host, db_name))
Session = sessionmaker(bind=engine)
session = Session()
def main():
from src.example import example_function
example_function()
if __name__ == '__main__':
main()
/src/example.py
(将会话导入另一个文件的示例):
from src import session
def example_function():
objects = session.query(ExampleTable).all()
但是,我正在努力查看如何确保在程序遇到异常无需且需要通过函数传递会话对象的异常时关闭该全局会话对象的情况。争论。
/src/__init__.py
(程序的入口点):
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine('mysql://%s:%s@%s/%s' % (username, password, host, db_name))
Session = sessionmaker(bind=engine)
def main(session):
from src.example import example_function
example_function(session)
if __name__ == '__main__':
try:
session = Session()
main(session)
finally:
session.close()
/src/example.py
(在另一个文件中使用会话对象的示例):
def example_function(session):
objects = session.query(ExampleTable).all()