简体   繁体   English

在sqlalchemy中关闭会话

[英]closing session in sqlalchemy

I have created a method in seperate python file. 我在单独的python文件中创建了一个方法。 Whenever I have to get any data from database I call this method. 每当我必须从数据库中获取任何数据时,我都会调用此方法。 Now I am doing a for loop where for every iteration, db call is made to below method for ex- 现在,我正在执行一个for循环,其中对于每次迭代,都会对以下方法进行db调用,例如

 def get_method(self, identifier):
        sess = session.get_session()
        id = sess.query(..).filter(I.. == ..)
        return list(id)[0]


def get_session():
    engine = create_engine('postgresql+psycopg2://postgres:postgres@localhost/db', echo=True)
    Session = sessionmaker(engine)
    sess = Session()
    return sess

I am getting FATAL: sorry, too many clients already , probably because I am not closing the sess object . 我越来越FATAL: sorry, too many clients already ,可能是因为我没有关闭sess对象。 Even after closing I am getting the same issue. 即使关闭后,我也遇到同样的问题。

How do I handle this. 我该如何处理。

You shouldn't be opening your session within the for loop. 您不应该在for循环中打开会话。 Do that before your loop begins, and close it after you're finished with your transactions. 在循环开始之前执行此操作,并在完成事务后将其关闭。 The documentation is helpful here: when to open and close sessions 该文档对您有帮助: 何时打开和关闭会话

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM