我正在Windows 10上使用Virtualbox / Vagrant并参加Udacity Full Stack开发人员课程。由于某些奇怪的原因,我无法通过我的python代码连接到数据库“ news”。这是我到目前为止的代码:
import psycopg2
DBNAME = "news"
#What are th most popular three articles of all time?
db = psycopg2.connect(dbname=DBNAME, port=5432) #connects to database
c = db.cursor()
c.execute("SELECT * FROM articles")
pop_articles = c.fetchall()
pop_articles
db.close()
这是我一直收到的错误,它使我发疯:
回溯(最近通话最近一次):
File "C:\Users\tom\Downloads\fsnd-virtual-machine\FSND-Virtual-Machine\vagrant\Trying\logs_analysis1.py", line 10, in <module>
db = psycopg2.connect(dbname=DBNAME, port=5432) #connects to database
File "C:\Users\tom\AppData\Local\Programs\Python\Python37\lib\site-packages\psycopg2\__init__.py", line 130, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: could not connect to server: Connection refused (0x0000274D/10061)
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused (0x0000274D/10061)
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
[Finished in 2.4s]
奇怪的是,我可以通过gitbash以及在vagrant目录中访问数据库,但是我无法获取python代码来返回任何内容而没有得到此错误。我唯一能想到的是数据库不允许连接我的代码,因为它来自虚拟机外部(即使此文件保存在vagrant目录中),我不得不以某种方式强制其在所有端口上侦听。不幸的是我没有postgres的密码,所以我不能更改配置以允许这样做。
任何提示或帮助将不胜感激。我已经为此工作了好几天。