为了账号安全,请及时绑定邮箱和手机立即绑定

Streamlit - 在线程中创建的 SQLite 对象只能在同一个线程中使用

Streamlit - 在线程中创建的 SQLite 对象只能在同一个线程中使用

侃侃尔雅 2022-12-06 14:57:49
我使用Streamlit作为我的数据处理和可视化框架。按照关于使用 Streamlit 进行高级缓存的文档,关于如何创建数据库连接并将它们传递给其他函数,我正在使用sqlite3并尝试在运行时创建一个连接并传递“光标”,方法是:import streamlit as st# create database connection@st.cache(allow_output_mutation=True)def get_database_connection():    conn = sqlite3.connect('collect/Data/fpl.db')    c = conn.cursor()       return c在这里,我尝试通过 传递我的连接 ID hash_funcs,返回创建的游标:# pass connections around@st.cache(allow_output_mutation=True, hash_funcs={sqlite3.Cursor:id})def get_teams_basic(c):    df_teams = sql('SELECT * FROM TeamsBasic', c)    return df_teams@st.cache(allow_output_mutation=True, hash_funcs={sqlite3.Cursor:id})def get_players_basic(c):       df_player_basic = sql('SELECT * FROM PlayersBasic', c)    return df_player_basic# and so on...这是我的sql():def sql(query, cursor):    '''    Takes an SQL query string, and outputs a    dataframe representation of the query result.    '''    # Execute the sql query    cursor.execute(query)    # Get the query into a dataframe and set columns    df_temp = pd.DataFrame(cursor.fetchall())    df_temp.columns = [x[0] for x in cursor.description]    # Set the sql id as the dataframe index    index_column = df_temp.columns[0]    df_temp.set_index(index_column, drop=True, inplace=True)    return df_temp然后,在 处main(),我实例化数据库连接并将光标传递给我的函数:def main():    c = get_database_connection()    teams(c)    players(c)if __name__ == '__main__':  main()但是当代码到达第二个连接时,players()出现以下错误:ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 123145444151296 and this is thread id 123145454661632.我错过了什么?
查看完整描述

1 回答

?
心有法竹

TA贡献1866条经验 获得超5个赞

我不确定您是否仍在解决这个问题,但如果您还在,我发现了一个可能有用的关于该主题的讨论线程。我很快就会在我的一个项目中试用它。

https://discuss.streamlit.io/t/prediction-analysis-and-creating-a-database/3504


查看完整回答
反对 回复 2022-12-06
  • 1 回答
  • 0 关注
  • 260 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信