Vagrant中的Django,psycopg2操作错误:无法连接到服务器:没有该文件或目录

0 投票
1 回答
3149 浏览
提问于 2025-04-17 14:15

在Vagrant虚拟机上,通过 apt-get install python-psycopg2 安装了Postgres数据库。测试导入时成功了。

$ python
Python 2.6.5 (r265:79063, Oct  1 2012, 22:04:36) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import psycopg2
>>> exit()

这是Django的设置文件:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': '/vagrant/v-root/projects/tdg/tdg/mydata.db',                      # Or path to database file if using sqlite3.
        'USER': 'username',                      # Not used with sqlite3.
        'PASSWORD': 'password',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

现在在新的Vagrant虚拟机上遇到了一个问题,找不到postgres_psycopg2。

$ python manage.py shell
Python 2.6.5 (r265:79063, Oct  1 2012, 22:04:36) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.db import connection
>>> cursor = connection.cursor()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python2.6/dist-packages/django/db/backends/__init__.py", line 306, in cursor
    cursor = self.make_debug_cursor(self._cursor())
  File "/usr/local/lib/python2.6/dist-packages/django/db/backends/postgresql_psycopg2/base.py", line 177, in _cursor
    self.connection = Database.connect(**conn_params)
OperationalError: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

>>> 

我运行了 netstat —listen,但是没有看到5432端口在监听。只有22(SSH)和8000(Django应用)在监听。

1 个回答

1

你并没有真正安装Postgres,只是安装了psycopg2,这是一个用于Postgres的Python客户端。你需要这样安装并运行Postgres:

apt-get install postgresql
/etc/init.d/postgresql start

(你可能还需要登录进去,为你的项目创建一个数据库,以便它可以进行交流)

撰写回答