Skip to main content
 首页 » 编程设计

python之验证 sqlalchemy session

2025年05月04日18jpfss

我正在使用 sqlalchemy 将值存储在我的数据库中。我想编写可以验证 session 的测试用例。

获取 session 对象的代码:

def get_session(): 
    Base = declarative_base() 
    engine = create_engine('postgresql+psycopg2://testdb:hello@localhost/mydatabase') 
    Base.metadata.bind = engine 
    DBSession = sessionmaker(bind=engine) 
    session = DBSession() 
    return session 

问题是即使我输入了错误的数据库名称,上面的代码仍然有效。当我尝试提交到数据库时,它会抛出一个错误 (OperationalError)。

我如何在创建过程中验证我的 session ?

请您参考如下方法:

def validate(session): 
    try: 
        # Try to get the underlying session connection, If you can get it, its up 
        connection = session.connection() 
        return True 
    except: 
        return False