Connect to a PostgreSQL database using environment variables.
| Returns: |
-
engine –
SQLAlchemy engine instance for the PostgreSQL connection.
|
Source code in api/database.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31 | def connect_to_postgres():
"""
Connect to a PostgreSQL database using environment variables.
Returns:
engine: SQLAlchemy engine instance for the PostgreSQL connection.
"""
load_dotenv()
# Define your PostgreSQL connection parameters
hostname = os.environ.get("SERVER")
database = os.environ.get("DATABASE")
username = os.environ.get("POSTGRES_USER")
password = os.environ.get("PASSWORD")
# Create a connection to the PostgreSQL database
connection_string = f"postgresql://{username}:{password}@{hostname}/{database}"
print(connection_string)
engine = create_engine(connection_string)
print(engine)
return engine
|