How can I check pooled connections in SQLAlchemy before handing them off to my application code?

只愿长相守 提交于 2019-12-10 13:22:15

问题


We have a slightly unreliable database server, for various reasons, and as a consequence sometimes the database connections used by my application vanish out from under it. The connections are SQLAlchemy 0.6.5 connections to a PostgreSQL db in a Pylons 1.0 web runtime.

What I want is some way to catch most of these without a user-visible error; ideally, I'd test the connection at the pool level before returning it from the engine. I control the creation of the engine, so I'm okay there.

What's the best (most idomatic / cleanest) way to accomplish this? I realize that there will always be the possibility of the connection dying between the check and the usage, but that's going to be pretty rare in this environment, and is therefore not a concern to me.


回答1:


You could use a pool listener:

class ConnectionChecker(sqlalchemy.interfaces.PoolListener):
    def checkout(self, dbapi_con, con_record, con_proxy):
        if not is_valid_connection(dbapi_con):
            # a new connection will be used
            raise sqlalchemy.exc.DisconnectionError 

Left for you is how to implement is_valid_connection for your use case.



来源:https://stackoverflow.com/questions/4649397/how-can-i-check-pooled-connections-in-sqlalchemy-before-handing-them-off-to-my-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!