Reputation: 473
I have created a method in seperate python file. 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-
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 . Even after closing I am getting the same issue.
How do I handle this.
Upvotes: 1
Views: 5318
Reputation: 161
You shouldn't be opening your session within the for loop. 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
Upvotes: 2