import os
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
engine=create_engine(os.getenv("DATABASE_URL"))
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()
回溯(最近通话最近): 文件“ list.py”,第6行,在 engine = create_engine(os.getenv(“ DATABASE_URL”)) 文件“ C:\ Users \ Aakash \ AppData \ Local \ Programs \ Python \ Python38-32 \ lib \ site-packages \ sqlalchemy \ engine__init __。py”, create_engine中的第479行 返回strategy.create(* args,** kwargs) 在创建的文件“ C:\ Users \ Aakash \ AppData \ Local \ Programs \ Python \ Python38-32 \ lib \ site-packages \ sqlalchemy \ engine \ strategies.py”中,行56 插件= u._instantiate_plugins(kwargs) AttributeError:“ NoneType”对象没有属性“ _instantiate_plugins”
如果将我的代码更改为:
答案 0 :(得分:2)
只需将其用作网址
“ PostgreSQL://用户名:密码@主机:端口/数据库”
将这些值直接传递到您的create_engine("postgresql://username:password@host:port/database")
我现在遇到了同样的问题,它对我有用。值得一提的是,在创建新用户和数据库并移动表之后,我完全得到了一个不同的错误。错误是'
''ModuleNotFoundError:没有名为'psycopg2''''
的模块
并且解决方案正在运行:pip3 install psycopg2-binary
PS:URL详细信息以及您的详细信息。
答案 1 :(得分:1)
看起来os.getenv("DATABASE_URL")
返回了None
。调用create_engine(None)
会给您这个错误。是否在您的环境变量中定义了DATABASE_URL
?
答案 2 :(得分:0)
代替
engine=create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))
输入您的网址:
engine = create_engine("postgresql://scott:tiger@localhost/mydatabase")
db = scoped_session(sessionmaker(bind=engine))
答案 3 :(得分:0)
为了避免在您的代码中输入您的 postgresql 连接(包括密码),请根据以下内容在终端中定义您的环境变量:
source ~/.bash_profile
或者您可以使用命令的简短形式:
. ~/.bash_profile
这将在当前 shell 中执行 .bash_profile 文件。
有关重新加载 .bash_profile 的其他建议可以在评论 here 中找到。