最近开始入行streamlit,用起来不要太爽,终于可以完全基于python从后端的数据处理到前端的可视化展示一条龙搞起来,大大加快了单兵生产力的产出。
streamlit本身是个单app的应用,背后是一个脚本从头到脚跑一遍。
于是出现了很多扩展应用,在streamlit的基础上扩展成多app的应用,今天试用了一下streamlit-multipage,可以做成多page的app,其实也没啥神秘的,本质就是通过pickle把一个页面的数据写成文件,再从另外一个页面加载的方式来实现页面之间的通信。
首先pip install streamlit-multipage安装,然后下载了一个计算BMI的源代码看效果。
from streamlit_multipage import MultiPage
def input_page(st, **state):
st.title("Body Mass Index")
weight_ = state["weight"] if "weight" in state else 0.0
weight = st.number_input("Your weight (Kg): ", value=weight_)
height_ = state["height"] if "height" in state else 0.0
height = st.number_input("Your height (m): ", value=height_)
if height and weight:
MultiPage.save({"weight": weight, "height": height})
def compute_page(st, **state):
st.title("Body Mass Index")
if "weight" not in state or "height" not in state:
st.warning("Enter your data before computing. Go to the Input Page")
return
weight = state["weight"]
height = state["height"]
st.metric("BMI", round(weight / height ** 2, 2))
app = MultiPage()
app.st = st
app.add_app("Input Page", input_page)
app.add_app("BMI Result", compute_page)
app.run()
遇到一个报错:
TypeError: file must have a 'write' attribute
搜了一下,应该是pickle.dump()引起的错:
when using pickle, file argument of pickle.dump must be a file object, not a string
也就是说pickle.dump()的对象,应该具有write的属性。那什么能有write的属性呢?答案是:文件。所以,streamlit-multipage.py中的:
pickling.dump(data, self.cache_file)
应该改成:
pickling.dump(data, open(self.cache_file, 'wb'))
另外一种解决方式是安装joblib。
本文安装joblib后,重启streamlit应用,确实能够解决问题。
参数输入页面:
BMI计算页面:
Nice!