Streamlit app keeps reseting with error

We are using Streamlit and streamlit-aggrid to render data, the application renders without issue when using VScode but when I execute the code directly with Streamlit it fails with errors below

Panda dataframes with 12 columns x 7689 rows
Columns are object, int64, float64

2023-02-01 07:37:29.262 Task exception was never retrieved
future: <Task finished name='Task-885' coro=<WebSocketProtocol13.write_message.<locals>.wrapper() done, defined at c:\dev\pocstrm01\lib\site-packages\tornado\websocket.py:1090> exception=WebSocketClosedError()>
Traceback (most recent call last):
  File "c:\dev\pocstrm01\lib\site-packages\tornado\websocket.py", line 1092, in wrapper
    await fut
tornado.iostream.StreamClosedError: Stream is closed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:\dev\pocstrm01\lib\site-packages\tornado\websocket.py", line 1094, in wrapper
    raise WebSocketClosedError()
tornado.websocket.WebSocketClosedError

Any assistance would be appreciated.

1 Like

Could you post a minimal reproducible code?

Also have a look on posting guide.

1 Like
  cs.execute(sqlquerystring)
  df= pd.DataFrame(cs.fetchall())
  selection = AgGrid(
        df,
        status_bar = True,
        gridOptions=gb.build(),
        allow_unsafe_jscode=True,
        enable_enterprise_modules=True,
        reload_data=True,
        key="WBgrid",
        conversion_errors="coerce"
    )
  st.session_state.exp = selection
1 Like

How do you execute with streamlit?

1 Like

In batch file streamlit run WBLanding.py --server.port 7777

1 Like

This one in is ok, how do you run that?

1 Like

Not sure what you mean, the batch file is executed in the context of an account which has admin privileges.

1 Like

I reread your initital post. I can see, the application renders without issue when using VScode … What do you mean by that?

1 Like

When executing within the VSCode environment the application renders and as such the errors do not display

1 Like

Can we see the contents of your requirements.txt file?

1 Like

I could not upload the file, pasted instead:

altair=4.2.0=pypi_0
anyjson=0.3.3=pyhd8ed1ab_1004
argon2-cffi=21.3.0=pyhd8ed1ab_0
argon2-cffi-bindings=21.2.0=py310he2412df_2
arrow=1.2.2=pyhd8ed1ab_0
asn1crypto=1.5.1=pypi_0
asttokens=2.0.5=pypi_0
attrs=22.1.0=pypi_0
babel=2.10.3=pyhd8ed1ab_0
backcall=0.2.0=pypi_0
bcrypt=3.2.2=py310he2412df_0
beautifulsoup4=4.11.1=pypi_0
blazeutils=0.6.5=pypi_0
bleach=5.0.1=pypi_0
blinker=1.5=pypi_0
boto3=1.24.89=pypi_0
botocore=1.27.89=pypi_0
brotli-python=1.0.9=py310h8a704f9_7
bzip2=1.0.8=he774522_0
ca-certificates=2022.9.24=h5b45459_0
cachetools=5.2.0=pypi_0
certifi=2022.9.24=pyhd8ed1ab_0
cffi=1.15.1=py310hcbf9ad4_0
charset-normalizer=2.1.0=pypi_0
click=8.1.3=py310h5588dad_0
colorama=0.4.5=pyhd8ed1ab_0
colour=0.1.5=py_0
commonmark=0.9.1=pypi_0
cryptography=36.0.2=pypi_0
dash=2.6.1=pyhd8ed1ab_0
debugpy=1.6.2=pypi_0
decorator=5.1.1=pypi_0
defusedxml=0.7.1=pypi_0
distlib=0.3.6=pypi_0
entrypoints=0.4=pypi_0
et_xmlfile=1.1.0=py310haa95532_0
executing=0.9.1=pypi_0
extra-streamlit-components=0.1.55=pypi_0
fastjsonschema=2.16.1=pypi_0
filelock=3.8.0=pypi_0
flake8=5.0.4=pypi_0
flask=2.2.2=pyhd8ed1ab_0
flask-compress=1.12=pyhd8ed1ab_0
flit-core=3.7.1=pyhd8ed1ab_0
formencode=2.0.1=pypi_0
furl=2.1.3=pyhd8ed1ab_0
future=0.18.2=pypi_0
git=2.34.1=haa95532_0
gitdb=4.0.9=pypi_0
gitpython=3.1.27=pypi_0
greenlet=1.1.2=py310h8a704f9_2
idna=3.3=pypi_0
importlib-metadata=4.12.0=pypi_0
infinity=1.5=pyhd8ed1ab_0
iniconfig=1.1.1=pypi_0
intel-openmp=2022.1.0=h57928b3_3787
intervals=0.9.2=pyhd8ed1ab_0
ipykernel=6.15.1=pypi_0
ipython=8.4.0=pypi_0
ipython-genutils=0.2.0=pypi_0
ipywidgets=7.7.1=pypi_0
itsdangerous=2.1.2=pyhd8ed1ab_0
jedi=0.18.1=pypi_0
jinja2=3.1.2=pyhd8ed1ab_1
jmespath=1.0.1=pypi_0
jsonschema=4.9.0=pypi_0
jupyter-client=7.3.4=pypi_0
jupyter-core=4.11.1=pypi_0
jupyterlab-pygments=0.2.2=pypi_0
jupyterlab-widgets=1.1.1=pypi_0
krb5=1.19.3=h1176d77_0
ldap3=2.9.1=pypi_0
libblas=3.9.0=8_mkl
libcblas=3.9.0=8_mkl
libffi=3.4.2=hd77b12b_4
liblapack=3.9.0=8_mkl
libpq=14.5=hfcc5ef8_0
libzlib=1.2.12=h8ffe710_2
markupsafe=2.1.1=py310he2412df_1
matplotlib-inline=0.1.3=pypi_0
mccabe=0.7.0=pypi_0
mistune=0.8.4=pypi_0
mkl=2020.4=hb70f87d_311
mock=4.0.3=pypi_0
mouseinfo=0.1.3=pypi_0
nbclient=0.6.6=pypi_0
nbconvert=6.5.0=pypi_0
nbformat=5.4.0=pypi_0
ndjson=0.3.1=pypi_0
nest-asyncio=1.5.5=pypi_0
notebook=6.4.12=pypi_0
numpy=1.23.1=py310h8a5b91a_0
openpyxl=3.0.9=pyhd3eb1b0_0
openssl=1.1.1q=h8ffe710_0
orderedmultidict=1.0.1=py_0
oscrypto=1.3.0=pypi_0
packaging=21.3=pypi_0
pandas=1.4.3=py310hf5e1058_0
pandocfilters=1.5.0=pypi_0
parso=0.8.3=pypi_0
passlib=1.7.4=pyh9f0ad1d_0
pendulum=2.1.2=py310he2412df_4
phonenumbers=8.12.53=pyhd8ed1ab_0
pickleshare=0.7.5=pypi_0
pillow=9.2.0=pypi_0
pip=22.2.2=pypi_0
platformdirs=2.5.2=pypi_0
plotly=5.10.0=pyhd8ed1ab_0
pluggy=1.0.0=pypi_0
prometheus-client=0.14.1=pypi_0
prompt-toolkit=3.0.30=pypi_0
protobuf=3.20.1=pypi_0
psutil=5.9.1=pypi_0
psycopg2=2.9.3=py310hcbf9ad4_0
psycopg2-binary=2.9.3=pyhd8ed1ab_0
pure-eval=0.2.2=pypi_0
py=1.11.0=pypi_0
py-linq=1.3.0=pypi_0
pyarrow=8.0.0=pypi_0
pyasn1=0.4.8=pypi_0
pyautogui=0.9.53=pypi_0
pycodestyle=2.9.1=pypi_0
pycparser=2.21=pyhd8ed1ab_0
pycryptodomex=3.15.0=pypi_0
pydeck=0.7.1=pypi_0
pyflakes=2.5.0=pypi_0
pygetwindow=0.0.9=pypi_0
pygments=2.12.0=pypi_0
pyjwt=2.4.0=pypi_0
pympler=1.0.1=pypi_0
pymsgbox=1.0.9=pypi_0
pyodbc=4.0.32=py310hd77b12b_1
pyopenssl=22.0.0=pypi_0
pyparsing=3.0.9=pypi_0
pyperclip=1.8.2=pypi_0
pyrect=0.2.0=pypi_0
pyrsistent=0.18.1=pypi_0
pyscreeze=0.1.28=pypi_0
pytest=7.1.3=pypi_0
python=3.10.4=hbb2ffb3_0
python-dateutil=2.8.2=pyhd8ed1ab_0
python-decouple=3.6=pypi_0
python_abi=3.10=2_cp310
pytweening=1.0.4=pypi_0
pytz=2022.1=py310haa95532_0
pytz-deprecation-shim=0.1.0.post0=pypi_0
pytzdata=2020.1=pyh9f0ad1d_0
pywin32=304=pypi_0
pywinpty=2.0.6=pypi_0
pyyaml=6.0=pypi_0
pyzmq=23.2.0=pypi_0
requests=2.28.1=pypi_0
rich=12.5.1=pypi_0
s3transfer=0.6.0=pypi_0
semver=2.13.0=pypi_0
send2trash=1.8.0=pypi_0
setuptools=61.2.0=py310haa95532_0
six=1.16.0=pyh6c4a22f_0
smmap=5.0.0=pypi_0
snowflake-connector-python=2.7.11=pypi_0
soupsieve=2.3.2.post1=pypi_0
sqlalchemy=1.4.40=py310he2412df_0
sqlalchemy-utils=0.38.2=pyhd8ed1ab_0
sqlite=3.38.5=h2bbff1b_0
stack-data=0.3.0=pypi_0
streamlit=1.14.0=pypi_0
streamlit-aggrid=0.3.3=pypi_0
streamlit-authenticator=0.2.1=pypi_0
streamlit-option-menu=0.3.2=pypi_0
tenacity=8.0.1=pyhd8ed1ab_0
terminado=0.15.0=pypi_0
tinycss2=1.1.1=pypi_0
tk=8.6.12=h2bbff1b_0
toml=0.10.2=pypi_0
tomli=2.0.1=pypi_0
toolz=0.12.0=pypi_0
tornado=6.2=pypi_0
tox=3.26.0=pypi_0
traitlets=5.3.0=pypi_0
typing_extensions=4.3.0=pyha770c72_0
tzdata=2022.1=pypi_0
tzlocal=4.2=pypi_0
urllib3=1.26.11=pypi_0
validators=0.20.0=pypi_0
vc=14.2=h21ff451_1
virtualenv=20.16.5=pypi_0
vs2015_runtime=14.27.29016=h5e58377_2
watchdog=2.1.9=pypi_0
wcwidth=0.2.5=pypi_0
webencodings=0.5.1=pypi_0
webgrid=0.4.9=pypi_0
werkzeug=2.2.2=pyhd8ed1ab_0
wheel=0.37.1=pyhd3eb1b0_0
widgetsnbextension=3.6.1=pypi_0
wincertstore=0.2=py310haa95532_2
wrapt=1.14.1=pypi_0
xz=5.2.5=h8cc25b3_1
zipp=3.8.1=pyhd8ed1ab_0
zlib=1.2.12=h8cc25b3_2

Can you run just:

streamlit run WBLanding.py
1 Like

The error persists

1 Like

Based from your code below. There seems to be no problem at all. Can you duplicate the error message by running that code?

cs.execute(sqlquerystring)
df= pd.DataFrame(cs.fetchall())
selection = AgGrid(
    df,
    status_bar = True,
    gridOptions=gb.build(),
    allow_unsafe_jscode=True,
    enable_enterprise_modules=True,
    reload_data=True,
    key="WBgrid",
    conversion_errors="coerce"
)
st.session_state.exp = selection
1 Like

This code produces the error when executed outside the VScode environment.

1 Like

It might be in:

cs.execute(sqlquerystring)

What is the exact error message?

So if this is run under vscode, there is no problem. If that is so, we need to find a block of code that can replicate the error message?

The supplied sample code produces the error.
The Sql is a select statement returning varchar, int64,float64 columns for displaying the data from snowflake database table.

Hi, I had the same problem. I’m running the app into a remote server, and It works fine for a few minutes and then crash and get this error. I don’t know what the problem is… till yesterday everything was working ok in my local

2023-02-24 12:41:43.796 Task exception was never retrieved
future: <Task finished name='Task-851' coro=<WebSocketProtocol13.write_message.<locals>.wrapper() done, defined at /home/gdeuser/miniconda3/envs/py310/lib/python3.10/site-packages/tornado/websocket.py:1090> exception=WebSocketClosedError()>
Traceback (most recent call last):
  File "/home/gdeuser/miniconda3/envs/py310/lib/python3.10/site-packages/tornado/websocket.py", line 1092, in wrapper
    await fut
tornado.iostream.StreamClosedError: Stream is closed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/gdeuser/miniconda3/envs/py310/lib/python3.10/site-packages/tornado/websocket.py", line 1094, in wrapper
    raise WebSocketClosedError()
tornado.websocket.WebSocketClosedError
2023-02-24 12:41:43.797 Task exception was never retrieved
future: <Task finished name='Task-856' coro=<WebSocketProtocol13.write_message.<locals>.wrapper() done, defined at /home/gdeuser/miniconda3/envs/py310/lib/python3.10/site-packages/tornado/websocket.py:1090> exception=WebSocketClosedError()>
Traceback (most recent call last):
  File "/home/gdeuser/miniconda3/envs/py310/lib/python3.10/site-packages/tornado/websocket.py", line 1092, in wrapper
    await fut
tornado.iostream.StreamClosedError: Stream is closed

My code is:

from pathlib import Path
import datetime
import pandas as pd
import plotly.express as px
import streamlit as st

st.set_page_config(
    page_title="Resistencia Hormigón",
    layout="wide",
    initial_sidebar_state='expanded')
with open('style.css') as f:
    st.markdown(f'<style>{f.read()}</style>', unsafe_allow_html=True)

@st.cache_data
def load_data():
    df = pd.read_parquet(Path(__file__).resolve().parents[1] / f'DHC_app/data/resistencias.parquet')
    return df
    
st.header(f'Resistencia de Hormigón')
df=load_data()

df.columns = df.columns.str.capitalize()
df = df.round(2)
df['Grupo_economico'] = df['Grupo_economico'].str.title()
df['Zona'] = df['Zona'].str.title()

with st.sidebar:
    count=0
    Fecha_inicio = st.date_input('Fecha inicio:', datetime.date(2022,1,1), min_value=datetime.date(2019,1,1), key=f'{count}_date')
    count += 1 
    Fecha_final = st.date_input('Fecha fin:', pd.to_datetime('today').date(), key=count)
    count += 1
    Fecha_inicio = str(pd.to_datetime(Fecha_inicio).date())
    Fecha_final = str(pd.to_datetime(Fecha_final).date())  
    df['Fecha'] = pd.to_datetime(df['Fecha']).dt.strftime('%Y-%m-%d')
    df = df.query(f'"{Fecha_inicio}" <= Fecha <= "{Fecha_final}"')


tabs = st.tabs(["Diferencia de Resistencia a 28 días"])#, "Cumplimiento de Resistencias", "7 vs 28 días"]) #"Cono", "Densidad",
tab_diferencia_resistencia = tabs[0]
#tab_cono = tabs[1]
#tab_densidad = tabs[2]

df = df.query(f'"{Fecha_inicio}" <= Fecha <= "{Fecha_final}"')


with tab_diferencia_resistencia:

    fig = px.strip(df, x='Fecha', y='Diff', color='Color', hover_data=['Tipo_hormigon', 'Resistencia_28'], color_discrete_map={
                "red": "red",
                "blue": "blue"})
    fig.update_layout(title={'text':f"<b>Diferencia entre Resistencia Hormigonera vs Resistencia Laboratorio</b>", 'x': 0.5,'xanchor':'center','yanchor':'top'}, width=800, height=500, margin=dict(l=20, r=20, t=100, b=20))
    fig.update_layout(showlegend=False)
    fig.add_hline(y=0, line_dash="dash")
    #fig.add_hrect(y0=400, y1=700, line_width=0, fillcolor="green", opacity=0.5)
    #fig.add_hrect(y0=-1, y1=-100, line_width=0, fillcolor="red", opacity=0.2)

    fig.update_layout(xaxis=dict(rangeselector=dict(buttons=list([dict(count=1,label="1m",step="month",stepmode="backward"),
                                                                        dict(count=6,label="6m",step="month",stepmode="backward"),
                                                                        dict(count=1,label="YTD",step="year",stepmode="todate"),
                                                                        dict(count=1,label="1y",step="year",stepmode="backward"),
                                                                        dict(step="all")])),
                                        rangeslider=dict(visible=True),
                                        type="date"))
    st.plotly_chart(fig)

    # Filtro de dataframe para mostrar solo diferencias negativas
    df1 = df.query('Diff<0')[['Zona', 'Fecha', 'Grupo_economico', 'Id_muestra', 'Tipo_hormigon', 'R_producto', 'Resistencia_7', 'Resistencia_28', 'Rel_28_fab', 'Diff']].sort_values(by="Diff")
    df1 = df1.rename(columns={"Grupo_economico": "Grupo Económico", "Id_muestra": "ID", "Tipo_hormigon": "Tipo de Hormigón", "R_producto": "Resistencia producto (MPa)", "Resistencia_7": "Resistencia a 7 días (MPa)", "Resistencia_28": "Resistencia a 28 días (MPa)", "Rel_28_fab": "Resistencia 28d/Prod (%)", "Diff": "Diferencia (MPa)"})
    st.dataframe(df1.style.format({"Resistencia producto (MPa)": "{:.1f}", "Resistencia a 7 días (MPa)": "{:.1f}", "Resistencia a 28 días (MPa)": "{:.1f}", "Resistencia 28d/Prod (%)": "{:.1%}", "Diferencia (MPa)": "{:.2f}"})) 

This seems to happen to me nondeterministically, and also in a remote context. If we could get some attention to this, that would be great!