Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

python - Error while connecting to postgresql using sqlalchemy

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

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 is the postgresql username and nehal is the password. How do I correct the error?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...