使用sqlalchemy连接到Postgresql时出错 [英] Error while connecting to postgresql using sqlalchemy

查看:195
本文介绍了使用sqlalchemy连接到Postgresql时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于与PostgreSQL数据库交互的python脚本(list.py)。

I have a python script(list.py) which is used to interact with postgresql database.

import os
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

engine = create_engine(os.getenv("postgresql://postgres:nehal@localhost:5432/lecture3"))
db = scoped_session(sessionmaker(bind=engine))

def main():
    flights = db.execute("SELECT origin, destination, duration FROM flights").fetchall()
    for flight in flights:
        print(f"{flight.origin} to {flight.destination}, {flight.duration} minutes.")

if __name__ == "__main__":
    main()

我在Ubuntu上安装了postgresql 16.04以讲课3作为数据库。当我以 python list.py 的代码执行代码时,出现以下错误:

I have postgresql installed on Ubuntu 16.04 with lecture3 as database.When I execute the code as python list.py,I get the following error:

Traceback (most recent call last):
  File "list.py", line 5, in <module>
    engine = create_engine(os.getenv("postgresql://postgres:nehal@localhost:5432/lecture3"))
  File "/home/nehal/anaconda3/lib/python3.6/site-packages/sqlalchemy/engine/__init__.py", line 424, in create_engine
    return strategy.create(*args, **kwargs)
  File "/home/nehal/anaconda3/lib/python3.6/site-packages/sqlalchemy/engine/strategies.py", line 52, in create
    plugins = u._instantiate_plugins(kwargs)
AttributeError: 'NoneType' object has no attribute '_instantiate_plugins'

postgres是postgresql用户名,nehal是密码。
如何纠正错误?

postgres is the postgresql username and nehal is the password. How do I correct the error?

推荐答案

os .getenv 用于获取环境变量的值,如果该变量不存在,则默认情况下返回 None 。您将连接字符串传递给它,(几乎可以肯定)该连接字符串作为环境变量不存在。因此它返回了 None ,该值已分配给 create_engine ,但由于期望连接字符串而失败。只需直接传递您的连接字符串即可:

os.getenv is used to get the value of an environment variable, and returns None by default if that variable doesn't exist. You're passing it your connection string, which (almost certainly) doesn't exist as an environment variable. So it's returning None, which is given to create_engine, which fails because it's expecting a connection string. Just pass your connection string in directly:

engine = create_engine("postgresql://postgres:nehal@localhost:5432/lecture3") 

这篇关于使用sqlalchemy连接到Postgresql时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆