File size: 803 Bytes
247d3db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
""""Create a connection to the database and return the engine and session objects."""

import os

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

HOST = os.getenv("DB_HOST")
PORT = os.getenv("DB_PORT")
DBNAME = os.getenv("DB_DATABASE")
USERNAME = os.getenv("DB_USERNAME")
PASSWORD = os.getenv("DB_PASSWORD")


def get_db_connection() -> tuple:
    """Create a connection to the database and return the engine and session objects.

    Returns:
        engine: connection to the database
        session: session to interact with the database
    """
    database_url = f"postgresql+psycopg2://{USERNAME}:{PASSWORD}@{HOST}:{PORT}/{DBNAME}"

    engine = create_engine(database_url)
    Session = sessionmaker(bind=engine)
    session = Session()

    return engine, session