如何使用sqlalchemy在Docker中访问postgresql?

如何使用sqlalchemy在Docker中访问postgresql?,postgresql,docker,sqlalchemy,Postgresql,Docker,Sqlalchemy,我正在尝试使用SQLAlchemy与停靠的PostgreSQL服务器交互。比如: engine = create_engine('postgresql://user:user_password@localhost:5432/database') df.to_sql('table', engine) 这给了我一个错误: OperationalError:(psycopg2.OperationalError)无法连接到服务器:连接被拒绝 服务器是否在主机“localhost”(::1)上运行并接受

我正在尝试使用SQLAlchemy与停靠的PostgreSQL服务器交互。比如:

engine = create_engine('postgresql://user:user_password@localhost:5432/database')
df.to_sql('table', engine)
这给了我一个错误:

OperationalError:(psycopg2.OperationalError)无法连接到服务器:连接被拒绝 服务器是否在主机“localhost”(::1)上运行并接受 端口5432上的TCP/IP连接? 无法连接到服务器:连接被拒绝 服务器是否在主机“localhost”(127.0.0.1)上运行并接受 端口5432上的TCP/IP连接


这表明Docker postgresql(正在运行)在该端口不可用。我尝试将
-p 5432:5432
添加到我的
docker compose exec
,但没有成功。有什么建议吗

由于flask应用程序和Postgres图像不在同一docker容器中,您无法通过localhost访问数据库

在数据库URL中,替换docker compose中Postgres服务的名称/

engine = create_engine('postgresql://user:user_password@{}:5432/database'.format('service_name_of_postgres'))

将SQLAlchemy与Docker上的PostgreSQL连接起来 大家好!让我尝试帮助您将Flask Web应用程序连接到PostgreSQL数据库,两者都运行在Docker上

在尝试复制和粘贴代码之前,请阅读所有内容 首先,您应该安装以下python模块:

  • 炼金术
  • psycopg2
您应该使用pip安装它们

psycopg2是将SQLAlchemy连接到PostgreSQL数据库所需的PostgreSQL驱动程序之一


我给你看我的docker-compose.yml文件


现在让我们看一下我的Python代码!这是一个test.py文件


如果您想了解更多信息,可以查看以下链接

  • 常规数据库连接url:
    方言+driver://username:password@主机:端口/数据库

  • 如果使用Docker,则需要替换Docker容器名称的主机值

version: '3'
services:

  web:
     #YourWebServiceConfiguration
     #YourWebServiceConfiguration
     #YourWebServiceConfiguration

  db_postgres:
    image: postgres:latest
    container_name: postgres_db_container
    ports:
        - "5432:5432"
    volumes:
        - postgres_db_vol:/var/lib/postgresql/data

    environment:
        POSTGRES_USER: yourUserDBName
        POSTGRES_PASSWORD: yourUserDBPassword
        POSTGRES_DB: yourDBName
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker


conn_url = 'postgresql+psycopg2://yourUserDBName:yourUserDBPassword@yourDBDockerContainerName/yourDBName'

engine = create_engine(conn_url)

db = scoped_session(sessionmaker(bind=engine))


query_rows = db.execute("SELECT * FROM anyTableName").fetchall()
for register in query_rows:
    print(f"{register.col_1_name}, {register.col_2_name}, ..., {register.col_n_name}")
    # Note that this Python way of printing is available in Python3 or more!!