This is an example of how to use SQLAlchemy to connect to a PostgreSQL database. The example includes a database class that manages the connection and session, a model class that represents a table in the database, and a utility class that gets the database URI from environment variables. You can either use local or dockerized Postgres instance.
- Clone the repository with command run
git clone git@github.com:brunolnetto/sqlalchemy-docker.git;
Make sure to install postgresql-contrib and postgresql-client for required postgres packages.
apt install postgresql-contrib postgresql-client- Install the dependencies: setup a virtual environment and install the dependencies
pip install virtualenv
virtualenv .venv
source .venv/bin/activate
pip install -r requirements.txtRun main code with command .venv/bin/python3 backend/app/main.py.
On the dockerized, you must first:
- Host database instance with command run:
docker run --name db -e POSTGRES_PASSWORD=mypassword -e POSTGRES_USER=myuser -e POSTGRES_DBNAME=mydb -p 5433:5433 -d postgresOR
docker compose up -d- Obtain container ip with command run
docker inspect db | jq -r '.[0].NetworkSettings.Networks[].IPAddress'; - Alter file
.envwith environment variablesPOSTGRES_HOSTto container ip andPOSTGRES_PORTas 5432 (the post on container network) by command run, below:
docker inspect db | jq -r '.[0].NetworkSettings.Networks[].IPAddress'- Run command
.venv/bin/python3 app/main.py