Skip to content

Commit

Permalink
update DBClient
Browse files Browse the repository at this point in the history
modify client to use mssql, mariadb and
postgresql
  • Loading branch information
nk-randers committed Oct 4, 2024
1 parent f731849 commit 56ffa89
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 27 deletions.
7 changes: 6 additions & 1 deletion src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@
import numpy as np
import altair as alt

# from utils.database import DatabaseClient # Uncomment when using database
# from utils.config import DB_HOST, DB_USER, DB_PASS, DB_NAME # Uncomment when using database

# db_client = DatabaseClient(db_type="mssql" ,database=DB_NAME, username=DB_USER, password=DB_PASS, host=DB_HOST) # Uncomment when using database

pd.set_option('display.max_columns', None)
st.set_page_config(page_title="Streamlit-Template", layout="wide")
st.title("Streamlit-Template")
Expand All @@ -19,7 +24,7 @@
'Product B': np.random.randint(30, 80, size=100),
'Product C': np.random.randint(20, 70, size=100)
})

data_long = data.melt('Day', var_name='Product', value_name='Sales')

line_chart = alt.Chart(data_long).mark_line().encode(
Expand Down
13 changes: 10 additions & 3 deletions src/utils/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,13 @@
PORT = os.getenv('PORT', '8080')
POD_NAME = os.getenv('POD_NAME', 'pod_name_not_set')

KEYCLOAK_URL = os.environ["KEYCLOAK_URL"].strip()
KEYCLOAK_REALM = os.environ["KEYCLOAK_REALM"].strip()
KEYCLOAK_CLIENT_ID = os.environ["KEYCLOAK_CLIENT_ID"].strip()
# Keycloack Auth
# KEYCLOAK_URL = os.environ["KEYCLOAK_URL"].strip()
# KEYCLOAK_REALM = os.environ["KEYCLOAK_REALM"].strip()
# KEYCLOAK_CLIENT_ID = os.environ["KEYCLOAK_CLIENT_ID"].strip()

# Database
DB_HOST = os.environ.get('DB_HOST')
DB_USER = os.environ.get('DB_USER')
DB_PASS = os.environ.get('DB_PASS')
DB_NAME = os.environ.get('DB_NAME')
44 changes: 21 additions & 23 deletions src/utils/database.py
Original file line number Diff line number Diff line change
@@ -1,38 +1,36 @@
import pymssql
import sqlalchemy
import logging


class DatabaseClient:
def __init__(self, database, username, password, host):
self.database = database
self.username = username
self.password = password
self.host = host
def __init__(self, db_type, database, username, password, host, port=None):
if db_type.lower() == 'mssql':
driver = 'mssql+pymssql'
elif db_type.lower() == 'mariadb':
driver = 'mariadb+mariadbconnector'
elif db_type.lower() == 'postgresql':
driver = 'postgresql+psycopg2'
else:
raise ValueError(f"Invalid database type {type}")

self.logger = logging.getLogger(__name__)

self.connection = None
self.cursor = None
if port:
host = host + f':{port}'

self.engine = sqlalchemy.create_engine(f'{driver}://{username}:{password}@{host}/{database}')

def get_connection(self):
try:
if not self.connection:
self.connection = pymssql.connect(host=self.host, user=self.username, password=self.password, database=self.database)
return self.connection
if self.engine:
return self.engine.connect()
self.logger.error("DatabaseClient not initialized properly. Engine is None. Check error from init.")
except Exception as e:
self.logger.error(f"Error connecting to database: {e}")

def get_cursor(self):
try:
if not self.cursor:
self.cursor = self.get_connection().cursor()
return self.cursor
except Exception as e:
self.logger.error(f"Error getting cursor: {e}")

def execute_sql(self, sql):
try:
cur = self.get_cursor()
cur.execute(sql)
return cur.fetchall()
with self.get_connection() as conn:
return conn.execute(sqlalchemy.text(sql))
except Exception as e:
self.logger.error(f"Error executing SQL: {e}")
self.logger.error(f"Error executing SQL: {e}")

0 comments on commit 56ffa89

Please sign in to comment.