有没有出现 数据库链接异常?

想请教一下,通过nohup streamlit run demo.py &后台命令启动服务后。几个小时后(约12h),有没有遇到访问URL出现数据库链接失败的情况吗?

Hey @YuxinHan258,

Not that I know of, what is your use case? Are you trying to keep your Streamlit app running locally indefinitely?

Happy Streamlit-ing!
Marisa

demo.py文件

import streamlit as st
import mysql.connector

# 初始化连接
@st.cache(allow_output_mutation=True, hash_funcs={"_thread.RLock": lambda _: None})
def init_connection():
    return mysql.connector.connect(**st.secrets["mysql"])

conn = init_connection()

# 查询
@st.cache(ttl=600)
def run_query(query):
    with conn.cursor() as cur:
        cur.execute(query)
        return cur.fetchall()

rows = run_query("SELECT * from mytable;")

for row in rows:
    st.write(f"{row[0]} has a :{row[1]}:")

后台运行 nohup streamlit run demo.py &
浏览器访问url可以正常使用,等几个小时后(12个小时)。再次访问url,提示 : OperationError: MySQL Connection not available

感谢帮忙。这个问题我已经解决了,不使用streamlit链接数据库,直接在脚本封装链接db的方法,这样后台运行就不会链接超时了。

1 Like