Connecting SQLAlchemy with PostgreSQL on Docker
Hello, guys! Let me try to help you to connect a Flask Web App to a PostgreSQL database, both running on Docker.
Please read everything before trying to copy and paste code
First of all you should have installed these python modules:
You should install them using pip.
psycopg2 is one of the PostgreSQL drivers needed to connect SQLAlchemy to your PostgreSQL database.
I'm showing you my docker-compose.yml file.
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
Now let's take a look at my python code! This is a test.py file.
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!!
If you want to learn more you can take a look at the following links.