因为我们需要使用不同的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/