Skip to content

Instantly share code, notes, and snippets.

@ivanleoncz
Last active January 19, 2023 05:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivanleoncz/a7d4f2125135ab4649825252e349aee0 to your computer and use it in GitHub Desktop.
Save ivanleoncz/a7d4f2125135ab4649825252e349aee0 to your computer and use it in GitHub Desktop.
Postgresql connector, using psycpg2 and environment variables (.env) loaded via python-dotenv.
# Example data, used for Docke Container environment.
DATABASE_USERNAME='postgres'
DATABASE_PASSWORD='postgres'
DATABASE_IP='172.17.0.2'
DATABASE_PORT='5432'
DATABASE_NAME='postgres'
import os
from dotenv import load_dotenv, find_dotenv
import psycopg2
load_dotenv(find_dotenv())
connection = psycopg2.connect(
user = os.getenv("DATABASE_USERNAME"),
password = os.getenv("DATABASE_PASSWORD"),
host = os.getenv("DATABASE_IP"),
port = os.getenv("DATABASE_PORT"),
database = os.getenv("DATABASE_NAME")
)
cursor = connection.cursor()
cursor.execute("SELECT version();")
record = cursor.fetchone()
print(f"Database Version: {record}")
psycopg2==2.8.6
python-dotenv==0.14.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment