AmateurDev
AmateurDev

Reputation: 129

Linking python app docker and postgress docker

I have two docker containers running by the following commands:

I have created the necessary user, database and table in my postgres (psql) container.

I am trying to run a python script:

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()

I get the following error:

  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)

I know one issue is that I need to set DATABASE_URL env - but I am not sure what should be that value

Upvotes: 1

Views: 85

Answers (2)

Izzno
Izzno

Reputation: 81

You need to specify the DATABASE_URL in the same environment you run your flask application.

Meaning if you run it from a CMD in windows, you need to export it before running flask:

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

Or in linux:

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

(port is usually 5432)

Then run your application.

Upvotes: 1

Oresztesz
Oresztesz

Reputation: 2430

Based on the documentation the DATABASE_URL environment variable should be something like this: postgresql://postgres:xyz@postgres:5432/postgres

Upvotes: 1

Related Questions