SQLAlchemy中的Zombie Connection

时间:2014-05-31 14:26:08

标签: python postgresql sqlalchemy

DBSession = sessionmaker(bind=self.engine)

def add_person(name):
    s = DBSession()
    s.add(Person(name=name))
    s.commit()

每次运行add_person()时,都会使用我的postgreSQL DB创建另一个连接。 看着:

SELECT count(*) FROM pg_stat_activity;

我看到计数上升,直到我收到Remaining connection slots are reserved for non-replication superuser connections错误。

如何杀死这些连接?我每次想要添加个人记录时打开一个新会话都错了吗?

1 个答案:

答案 0 :(得分:0)

通常,您应该保留Session对象(此处为DBSessionseparate from any functions that make changes to the database。所以在你的情况下,你可能会尝试这样的事情:

DBSession = sessionmaker(bind=self.engine)
session = DBSession()  # create your session outside of functions that will modify database

def add_person(name):
    session.add(Person(name=name))
    session.commit()

现在,每次将人员添加到数据库时,您都不会获得新的连接。