python-3.x - 未提取SQLAlchemy OperationalError

标签 python-3.x error-handling sqlalchemy

因为我们需要使用不同的URL来访问数据库以供内部和外部使用,所以我实现了以下代码。问题是,try/except子句未提取引发的OperationalError。为什么未提取此错误?

try:
    return create_engine('postgresql://{user}:{password}@{host}:{port}/{dbname}'.format(
            dbname="db_name",
            user="username",
            host="internal_url.com",
            port=1234,
            password="PassWord"))
except exc.OperationalError:
    return create_engine('postgresql://{user}:{password}@{host}:{port}/{dbname}'.format(
            dbname="db_name",
            user="username",
            host="external_url.com",
            port=1234,
            password="PassWord"))

最佳答案

create_engine仅创建实例,但不建立连接。
您需要连接到数据库以验证连接是否有效。像这样

try:
    engine = create_engine('postgresql://{user}:{password}@{host}:{port}/{dbname}'.format(
            dbname="db_name",
            user="username",
            host="internal_url.com",
            port=1234,
            password="PassWord"))
    engine.connect()
    return engine
except sqlalchemy.exc.OperationalError:
    return create_engine('postgresql://{user}:{password}@{host}:{port}/{dbname}'.format(
            dbname="db_name",
            user="username",
            host="external_url.com",
            port=1234,
            password="PassWord"))

关于python-3.x - 未提取SQLAlchemy OperationalError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63283246/

相关文章:

java - 非法开始表达错误和编译困难

sqlalchemy - 如何将带有子查询的查询转换为关系

python - SQLAlchemy:AttributeError:无法在列 '_sa_instance_state' 的行中找到列

python - 使用自定义名称将多个 pandas DataFrames 输出到 CSV

python - 在 Tkinter Canvas 中删除多边形内的区域

vba - On Error 尽管没有生成错误,但 GoTo 语句仍在执行

python - SQLAlchemy:查询数据库时遇到困难

python - 为什么正则表达式模式不仅仅在Python中匹配?

python-3.x - 标记默认月份 - python pandas

node.js - 如何按照存储库模式从 nodeJS 应用程序中的服务和存储库中抛出错误