簡體   English   中英

本地 postgresql 環境未與 sqlalchemy 連接

[英]local postgresql environment doesn't connect with sqlalchemy

我有一個名為 list.py 的 python 代碼,用於與名為 data_sample 的本地 postgresql 數據庫交互。 這是我的代碼:

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

engine = create_engine(os.getenv("data_sample"))
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()

當我將代碼作為 python list.py 執行時,我收到以下錯誤:

Traceback (most recent call last):
  File "list.py", line 6, in <module>
    engine = create_engine(os.getenv("data_sample"))
  File "/Users/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages  /sqlalchemy/engine/__init__.py", line 500, in create_engine
    return strategy.create(*args, **kwargs)
  File "/Users/admin/.pyenv/versions/3.7.3/lib/python3.7/site-packages/sqlalchemy/engine/strategies.py", line 56, in create
    plugins = u._instantiate_plugins(kwargs)
AttributeError: 'NoneType' object has no attribute '_instantiate_plugins'

似乎它不知道我的名為 data_sample 的數據庫。 我該如何解決?

參考這個鏈接

os.getenv 用於獲取環境變量的值

改用這個:

engine = create_engine("postgresql://username:password@localhost:port/name_of_database")

如果您沒有更改默認設置,那么您的用戶名將是 postgres,端口將是 5432。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM