如何使用 streamlit 缓存将数据库连接作为输入的函数

How to cache a function that takes a database connection as an input using streamlit

我有一个数据库连接:

import sqlalchemy as sa

engine = sa.create_engine('my_info')
connection = engine.connect()

后续我有一个功能:

import pandas as pd

def load_data(connection):
    sql = 'select * from tablename'
    df = pd.read_sql(sql, con = connection)
    return df

这是我正在开发的 Streamlit 应用程序的一部分,我需要 streamlit 来缓存我的 load_data 函数的输出。我认为它是这样工作的:

import pandas as pd
import streamlit as st

@st.cache()
def load_data(connection):
    sql = 'select * from tablename'
    df = pd.read_sql(sql, con = connection)
    return df

但这给了我以下错误:

UnhashableTypeError: Cannot hash object of type builtins.weakref, found in the arguments of load_data().

错误要长得多,如果有帮助,我会post。该错误还包含 a link to the streamlit documentation。我阅读了它并重新编写了我的代码,如下所示:

@st.cache()
def DBConnection():
    engine = sa.create_engine("my_info")
    conn = engine.connect()
    return conn
conn = DBConnection()

@st.cache(hash_funcs={DBConnection: id})
def load_data(connection):
        sql = 'select * from tablename'
        df = pd.read_sql(sql, con = connection)
        return df

但这给了我一个 NameError:

NameError: name 'DBConnection' is not defined

我 运行 没法尝试,如有任何帮助,我们将不胜感激。很可能我误解了文档,因为它假设了很多关于散列和缓存过程的先验知识。

结合两种方法使用:

@st.cache(allow_output_mutation=true)

代码:

@st.cache(allow_output_mutation=true)
def load_data():
    engine = sa.create_engine("my_info")
    conn = engine.connect()
    sql = 'select * from tablename'
    df = pd.read_sql(sql, con = conn )
    return df

更多内容请阅读documentation