if you used PostreSQL in docker, for example
docker pull postgres
mkdir -p $HOME/docker/volumes/postgres
docker run --rm --name pg-docker -e POSTGRES_PASSWORD=docker -d -p 5432:5432 -v $HOME/docker/volumes/postgres:/var/lib/postgresql/data postgres
$ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
850f9ee04731 postgres "docker-entrypoint.s…" 44 hours ago Up 44 hours 0.0.0.0:5432->5432/tcp pg-docker
you don't install psycopg2, for this variant you can install psycopg2-binary
pip install psycopg2-binary
after can use for example
import psycopg2
connection = psycopg2.connect(database="postgres", user='postgres', password='docker', host="localhost", port=5432)
cursor = connection.cursor()
sql_context ="""
select
*
from
public.metrics sm
where
sm.metric_name not like '%test%'
group by
sm.metric_name
"""
cursor.execute(sql_context)
# Fetch all rows from database
record = cursor.fetchall()
print("Data from Database:- ", record)