【问题标题】:Linking python app docker and postgress docker链接 python app docker 和 postgres docker
【发布时间】:2019-02-01 06:07:21
【问题描述】:

我有两个通过以下命令运行的 docker 容器:

  • docker run --name postgres -v "/Users/xxx/Desktop/Coding/DockerMounting":/home/ -e POSTGRES_PASSWORD=xyz -d postgres

  • docker run -it -v "/Users/xxx/Desktop/Coding/DockerMounting":/home/t -p 5000:5000 --name some-app --link postgres:postgres -d xxx/ ubuntu:最新的

我已经在我的 postgres (psql) 容器中创建了必要的用户、数据库和表。

我正在尝试运行 python 脚本:

import os

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

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

我收到以下错误:

  File "list.py", line 6, in <module>
    engine = create_engine(os.getenv("DATABASE_URL"))
  File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/__init__.py", line 435, in create_engine
    return strategy.create(*args, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/strategies.py", line 56, in create
    plugins = u._instantiate_plugins(kwargs)

我知道一个问题是我需要设置 DATABASE_URL 环境 - 但我不确定该值应该是什么

【问题讨论】:

    标签: python postgresql docker


    【解决方案1】:

    基于documentationDATABASE_URL 环境变量应该是这样的:postgresql://postgres:xyz@postgres:5432/postgres

    【讨论】:

    • @dipesh-sukhani:供进一步参考,如果解决了问题,请考虑接受答案。
    【解决方案2】:

    您需要在运行烧瓶应用程序的同一环境中指定 DATABASE_URL。

    意思是如果你在windows中从CMD运行它,你需要在运行flask之前导出它:

    setx DATABASE_URL "postgres://<user>:<password>@<host>:<port>/<DBname>"
    

    或者在linux中:

    export DATABASE_URL=postgres://<user>:<password>@<host>:<port>/<DBname>
    

    (端口通常是5432)

    然后运行您的应用程序。

    【讨论】:

      猜你喜欢
      • 2022-11-05
      • 2021-07-17
      • 1970-01-01
      • 1970-01-01
      • 2021-05-21
      • 1970-01-01
      • 2021-01-26
      • 1970-01-01
      • 2021-07-25
      相关资源
      最近更新 更多