我已经使用Docker和以下命令在我的计算机上设置了一个临时Postgres数据库用于测试目的:
1)
sudo docker run --name some-postgres6 -e POSTGRES_PASSWORD=mysecretpassword -p 5430:5432 postgres:9.1 -d postgres
2)
sudo docker run -it --rm --link some-postgres6:postgres postgres psql -h postgres -U postgres
我想使用Python连接到数据库:
from sqlalchemy.engine import create_engine
import psycopg2
engine = create_engine('postgresql+psycopg2://postgres:mysecretpassword@localhost/mydb?port=5432') ### IMPORTANT!!!
connection = engine.connect()
然后我收到了这个错误:
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?
这段代码用于在我运行Ubuntu的其他机器上工作。我猜这与windows有关。我正在运行Windows 10 Home(没有Windows经验)并使用Docker工具箱。
答案 0 :(得分:3)
我终于弄明白了这个问题。它是" localhost ",127.0.0.1上没有运行任何内容。
我不得不将其更改为docker机器的IP。如果您打开 Docker快速入门终端,则会显示此信息。它显示类似" function Message(message) {
this.message = message
}
Message.prototype.log = function() {
if (this.color) {
console.log('<' + this.color + '>', this.message)
} else {
console.log(this.message)
}
}
// Padded
function Padded(message) {
Message.call(this, message)
this.padded = true
}
Padded.prototype = Object.create(Message.prototype)
Padded.prototype.constructor = Padded
Padded.prototype.log = function() {
console.log(`\n${this.message}\n`)
}
// Success
function Success(message) {
Message.call(this, message)
this.color = 'green'
}
Success.prototype = Object.create(Message.prototype)
// Here I try to assign one prototype property to another. Which does not work.
Success.prototype.padded = Padded.prototype.log
Success.prototype.constructor = Success
// Error
function Error(message) {
Message.call(this, message)
this.color = 'red'
}
Error.prototype = Object.create(Message.prototype)
Error.prototype.constructor = Error
const log = {
success: (msg) => new Success(msg).log(),
error: (msg) => new Error(msg).log()
}
// Here I want to be able to 'pad' a log by accessing the `padded` property on the `Success.prototype` object.
//log.success.padded('test success')
log.success('Test success')
log.error('test error')
&#34;
查找此IP的另一种方法是打开 资源监视器 ,转到网络标签,然后检查 TCP连接。应该docker is configured to use the default machine with IP 192.168.XX.XXX
正在运行。远程地址列中显示的IP是可以工作的IP。
最后正确的命令:
docker.exe
答案 1 :(得分:0)
不确定这只是您示例中的拼写错误,但是您将第一个代码段中的postgres容器映射到端口5430.如果这是正确的,则必须将连接字符串更改为以下内容:
engine = create_engine('postgresql+psycopg2://postgres:mysecretpassword@localhost/mydb?port=5430') ### IMPORTANT!!!