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

查看:48
本文介绍了使用 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 16.04 上安装了 postgresql,并使用了 Lease3 作为数据库.当我将代码作为 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天全站免登陆