i have a CRUD streamlit app that read from database and update the values and i am using the streamlit ag-grid
package in order to display the table.
The problem is that once the user update the value in the datafarme its updated on the Database but still displaying the old value on the streamlit app
Unless i stop the app and rerun it again.
how can i fix this i know that i must use st.session_state
but i did not know how and where to use it in order to return the updated value.
code:
import streamlit as st
import pyodbc
import pandas as pd
import numpy as np
# aggrid pckgs
from st_aggrid import AgGrid,GridOptionsBuilder,JsCode
from st_aggrid import GridUpdateMode,DataReturnMode
# connect to DB
@st.experimental_singleton
def connect_db():
try:
con = pyodbc.connect(
driver = "ODBC Driver 17 for SQL Server",
Server="192.168.111.67",
DATABASE="FTF",
UID="XXXXX",
PWD="XXXXXX",
)
cursor = con.cursor()
except Exception as e:
st.write("error is: {}".format(e))
return con
con = connect_db()
df = pd.read_sql_query('''select m.ID,
m.name
from profile m
''',con,)
def display_aggrid(dff):
with con.cursor()as cur:
gd = GridOptionsBuilder.from_dataframe(dff)
gridoptions = gd.build()
grid_table = AgGrid(dff,gridOptions=gridoptions,
reload_data=True,
data_return_mode=DataReturnMode.AS_INPUT,
update_mode=GridUpdateMode.MODEL_CHANGED, # function for change value
allow_unsafe_jscode=True, # ==> allow js code
fit_columns_on_grid_load=True, # ==> fit the columns width with the grid
enable_enterprise_modules=True # enable this line will allow to add sidebar (filter and groupby)
)
if st.sidebar.button("UPDATE"):
try:
for i in range (dff.shape[0]):
if dff.iloc[i]['name'] != grid_table['data']['name'][i]:
query_name = """UPDATE [profile][profile_info]
SET
name = ?,
modified_date = ?
WHERE ID = ?
"""
id= int(dff.iloc[i]['ID'])
name= grid_table['data']['name'][i]
modified_date = datetime.datetime.now().date()
cur.execute(query_name,
name,
modified_date,
id)
cur.commit()
st.sidebar.success("Update done")
except Exception as e:
st.write("error after updating is: {}".format(e))
return grid_table['data']
def main():
result = df
display_aggrid(result)
if __name__=='__main__':
main()