已安装Peewee与PostgreSQL,FastAPI建表时报Postgres驱动未安装错误
解决Peewee连接PostgreSQL时的驱动缺失错误
核心问题
你遇到的peewee.ImproperlyConfigured: Postgres driver not installed!错误,本质是Peewee连接PostgreSQL必须依赖psycopg2驱动包,而你的当前环境未安装该依赖。
解决方案步骤
安装PostgreSQL驱动
直接通过pip安装适配的驱动包,开发环境推荐用psycopg2-binary(无需本地编译,快速安装):pip install psycopg2-binary生产环境可选择官方的
psycopg2(需提前安装PostgreSQL开发库):pip install psycopg2修正代码中的两处错误
create_tables参数格式错误:该方法接受一个包含所有表的列表,而非两个独立列表,将
修改为:db.create_tables([User],[Plan])db.create_tables([User, Plan])- 重复定义
db:你从models.schema导入了db,又重新创建了PostgresqlDatabase实例,需确保User和Plan模型绑定的是同一个数据库连接。建议删除重复定义,直接使用models.schema中的db,或在模型文件中绑定当前定义的连接实例。
优化数据库连接(可选)
在FastAPI中建议通过上下文管理器或依赖管理数据库连接,避免资源泄漏,示例修改SetupDB函数:@app.get('/setup_db') async def SetupDB(): try: db.connect() db.create_tables([User, Plan]) new_user = User.create( username='user1', email='user1@email.com', hashed_password='pwd####', create_on=datetime(2001, 3, 29, 5, 15, 30) ) return {"user_id": new_user.id, "username": new_user.username} finally: if not db.is_closed(): db.close()
内容的提问来源于stack exchange,提问作者Saash
相关产品推荐
相关产品推荐

