Skip to content
Snippets Groups Projects
Commit 9c3915a0 authored by Ryan Melvin's avatar Ryan Melvin
Browse files

db test integrated into app

parent 16625b34
No related branches found
No related tags found
1 merge request!2Docker db secrets
import streamlit as st
import pyodbc
import os
def manage_sensitive(name):
secret_fpath = f'/run/secrets/{name}'
existence = os.path.exists(secret_fpath)
if existence:
v2 = open(secret_fpath).read().rstrip('\n')
return v2
if not existence:
return KeyError(f'{name}')
DB_SERVER = manage_sensitive("db_server")
DB_NAME = manage_sensitive("db_name")
DB_USER = manage_sensitive("db_user")
DB_PASSWORD = manage_sensitive("db_password")
OPENAI_API_KEY = manage_sensitive("openai_api_key")
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
# Initialize db connection.
# Uses st.cache_resource to only run once.
@st.cache_resource
def init_connection():
return pyodbc.connect(
"DRIVER={ODBC Driver 17 for SQL Server};SERVER="
+ DB_SERVER
+ ";DATABASE="
+ DB_NAME
+ ";UID="
+ DB_USER
+ ";PWD="
+ DB_PASSWORD
)
if st.button("test"):
conn = init_connection()
# Perform query.
# Uses st.cache_data to only rerun when the query changes or after 10 min.
@st.cache_data(ttl=600)
def run_query(query):
with conn.cursor() as cur:
cur.execute(query)
return cur.fetchall()
rows = run_query("SELECT TOP 2 * from DS_apps.dbo.test_table;")
# Print results.
for row in rows:
st.write(f"{row[1]}")
conn.close()
# write
# Insert more example rows into DS_apps.dbo.test_table
# cursor = conn.cursor()
# # Insert a single example row into DS_apps.dbo.test_table
# insert_query = """
# INSERT INTO DS_apps.dbo.test_table (name, age, city)
# VALUES ('Emily White', 31, 'San Diego');
# """
# cursor.execute(insert_query)
# conn.commit()
# # Close the cursor and connection
# cursor.close()
# conn.close()
# print("Data inserted successfully.")
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment