简体   繁体   English

使用 sqlalchemy 连接到 postgresql 时出错

[英]Error while connecting to postgresql using sqlalchemy

I have a python script(list.py) which is used to interact with postgresql database.我有一个用于与 postgresql 数据库交互的 python 脚本(list.py)。

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()

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:我在 Ubuntu 16.04 上安装了 postgresql,以讲座 3 作为数据库。当我将代码作为python list.py执行时,出现以下错误:

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 is the postgresql username and nehal is the password. postgres 是 postgresql 用户名, nehal 是密码。 How do I correct the error?我该如何纠正错误?

os.getenv is used to get the value of an environment variable, and returns None by default if that variable doesn't exist. os.getenv用于获取环境变量的值,如果该变量不存在,则默认返回None 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.所以它返回None ,它被赋予create_engine ,它失败,因为它期待一个连接字符串。 Just pass your connection string in directly:只需直接传递您的连接字符串:

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

我会尝试在没有getenv情况下运行它,这似乎没用并且可能返回None

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

This work for me:这对我有用:

export DATABASE_URL="postgres://localhost/lecture3"
export DATABASE_URL="postgres://localhost:5432/lecture3"
export DATABASE_URL="postgres:///lecture3"

You should use this command in your ENV.你应该在你的 ENV 中使用这个命令。

Do this before running $ python list.py where在运行 $ python list.py where 之前执行此操作

 username your psql username password your psql password server localhost or remote server port 5432 database your psql database
(flask) $ export DATABASE_URL="postgresql://username:password@localhost:5432/database"

Verify:核实:

(flask) $ echo $DATABASE_URL

Run:跑:

$ python list.py

For me the below worked perfectly without any issues对我来说,下面的工作完美无缺

engine = create_engine("postgres://postgres:password@localhost:5432")

where "password" shall be substituted for your PostgreSQL password you used while installing PostgreSQL.其中“密码”应替换您在安装 PostgreSQL 时使用的 PostgreSQL 密码。

If you are using windows then setting up in System Variable would resolve the issue.如果您使用的是 Windows,则在系统变量中进行设置将解决该问题。 For example on windows 7: click start and type computer, it will bring up computer program, click computer and it will open up computer program, click on "system properties" tab then it will bring up system properties application, now click the "Advanced" tab then you need to click the "Environment Variables" tab, it will open the dialog box which will have user variables and system variables.以windows 7为例:点击开始,输入电脑,会弹出电脑程序,点击电脑,会打开电脑程序,点击“系统属性”选项卡,会弹出系统属性应用程序,现在点击“高级” ”选项卡,然后您需要单击“环境变量”选项卡,它将打开包含用户变量和系统变量的对话框。 Click the "New" tab on system variables and then type "DATABASE_URL" in variable name and "postgres+psycopg2://postgres:password@localhost:5432/postgres" in Variable value.单击系统变量上的“新建”选项卡,然后在变量名中键入“DATABASE_URL”,在变量值中键入“postgres+psycopg2://postgres:password@localhost:5432/postgres”。 Clike "OK" Open new command prompt using cmd. Clike "OK" 使用 cmd 打开新的命令提示符。 Change directory to the directory where your list.py program exist.将目录更改为 list.py 程序所在的目录。 in my case I have it in c:\\cs50\\src3 so after opening the cmd then cd c:\\cs50\\src3.在我的情况下,我将它放在 c:\\cs50\\src3 中,所以在打开 cmd 然后 cd c:\\cs50\\src3 之后。 then execute python list.py you will see your results like然后执行 python list.py 你会看到你的结果

enter image description here在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM