使用SQLAlchemy连接PostgreSQL到Discord bot时出现KeyError如何解决
问题排查与解决方案
错误根本原因
os.environ[] 是Python用于读取系统环境变量的方法,括号内需传入环境变量的键名,你将完整的PostgreSQL连接字符串直接作为键名传入,系统中不存在对应名称的环境变量,因此抛出KeyError。
修复方案
二选一即可:
方案1:直接传入连接字符串(适合本地测试场景)
无需读取环境变量,直接去掉代码中的os.environ[]包裹即可,修改后代码如下:
def migrate(): # TODO This should be removed in favor of a true database migration tool like Alembic # We create the engine to connect to the database engine = sqlalchemy.create_engine("postgresql+psycopg2://postgres:password@localhost:5432/yohouse-yodismo")
方案2:通过环境变量读取连接串(适合生产环境,避免敏感信息硬编码)
- 首先在运行代码的环境中新增环境变量:
- Windows临时生效:CMD执行
set DATABASE_URL=postgresql+psycopg2://postgres:password@localhost:5432/yohouse-yodismo - Linux/Mac临时生效:终端执行
export DATABASE_URL=postgresql+psycopg2://postgres:password@localhost:5432/yohouse-yodismo - 需要永久生效则将上述命令写入对应系统的环境变量配置文件中即可
- Windows临时生效:CMD执行
- 其次修改代码读取该环境变量:
def migrate(): # TODO This should be removed in favor of a true database migration tool like Alembic # We create the engine to connect to the database engine = sqlalchemy.create_engine(os.environ["DATABASE_URL"])
后续验证
修改后重新运行代码,如果出现数据库连接报错,按顺序排查:
- 本地PostgreSQL服务已正常启动,且运行端口为5432
- 数据库账号
postgres的密码与代码中填写的password一致 - 已提前手动创建名为
yohouse-yodismo的数据库,SQLAlchemy不会自动创建数据库,仅会自动创建定义好的表结构
内容的提问来源于stack exchange,提问作者gab
相关产品推荐
相关产品推荐

