美文网首页
streamlit如何实现多页面

streamlit如何实现多页面

作者: 风逝流沙 | 来源:发表于2022-05-15 21:30 被阅读0次

0 引入

我们在streamlit搭建ML前端demo这篇文章里简单介绍了streamlit这个搭建前端页面的神器。我们可以通过python脚本编写实现一个简单的展示页面。那如果你同时有N个页面想要去展示,应该怎么样去做呢?今天就探讨一下怎样利用streamlit实现多页面展示。

1 脑洞大开

我在这里列了几种可以实现多页面展示的方法,供大家参考。

  1. 通过server.port参数指定运行端口,同时开多个页面。
  2. 多个页面合并在一个页面内,通过某个组件实现页面跳转。
  3. 看看有没有开源工具包可以用,避免重复造轮子。
    下面就来讲下这几种实现方法。

2 多页面实现

2.1 同时开多个页面

我们之前在streamlit搭建ML前端demo里介绍过,streamlit运行的时候是通过命令行执行服务启动命令的。运行命令如下

streamlit run your_script.py [-- script args]

注意:这里传入自己需要用到的参数时,必须使用双横线,否则参数就被视为streamlit的参数,而非你脚本的参数。

也可以传入配置选项来修改应用端口、禁用自动保存等特性。要查看可用选型,运行 如下命令:

streamlit run --help

执行后的结果如下图所示:


配置选项

这里的--global.disableWatchdogWarning就是streamlit的一个配置选项,类型是BOOLEAN,下边是对这个参数的描述。

那我们可以找到--server.port这个参数,它是INTEGER类型的。运行不同app.py脚本的时候,指定一下这个参数即可。

streamlit run app.py --server.port 5002

就可以看到这个页面是在5002端口启动的。


server.port参数

2.2 多页面跳转

我主要参考了这个github提到的多页面配置办法。通过新建一个MultiApp类,做多个页面的添加和运行,这样只需要在一个端口运行服务。

那如何在不同页面之间跳转呢?那就需要用到streamlit内置的一些前端组件了,如st.sidebar.selectbox(显示列表选择框)或者st.sidebar.radio(显示单选框)。就可以实现多个页面之间跳转了。

来,上代码,咱们学习下人家的idea。

import streamlit as st

class MultiApp:
    """Framework for combining multiple streamlit applications.
    Usage:
        def foo():
            st.title("Hello Foo")
        def bar():
            st.title("Hello Bar")
        app = MultiApp()
        app.add_app("Foo", foo)
        app.add_app("Bar", bar)
        app.run()
    It is also possible keep each application in a separate file.
        import foo
        import bar
        app = MultiApp()
        app.add_app("Foo", foo.app)
        app.add_app("Bar", bar.app)
        app.run()
    """
    def __init__(self):
        self.apps = []

    def add_app(self, title, func):
        """Adds a new application.
        Parameters
        ----------
        func:
            the python function to render this app.
        title:
            title of the app. Appears in the dropdown in the sidebar.
        """
        self.apps.append({
            "title": title,
            "function": func
        })

    def run(self):
        app = st.sidebar.radio(
            'Go To',
            self.apps,
            format_func=lambda app: app['title'])

        app['function']()

其实很简单,去除注释,代码没几行。主要实现的功能是,通过一个列表apps存储不同的页面,利用st.sidebar.radio选择title对应的页面function并执行。每个页面有一个title和一个function组成,这里的function是每个页面上需要展示的内容。

那我们自己运行一下他给的例子吧,代码如下。

def foo():
    st.title("Hello Foo")
def bar():
    st.title("Hello Bar")
app = MultiApp()
app.add_app("Foo", foo)
app.add_app("Bar", bar)
app.run()

执行下,默认是选择了第一个页面Foo,咱们点击第二个Bar,也能跳转到第二个页面上去。


第一个页面 第二个页面

再来点击下第一个Foo,结果发现,哎,页面展示的不对劲。怎么内容还停留在第二个页面呢。


再次点击第一个页面

再去命令行里边看看,里边也有报错。报错内容如下:

报错信息

去github看看有没有issue,还真找到一个同样的问题。看里边作者提供的解决方案是,重写了run()函数,重写后的代码内容如下。

    def run(self):
        app_state = st.experimental_get_query_params()
        app_state = {k: v[0] if isinstance(v, list) else v for k, v in app_state.items()} # fetch the first item in each query string as we don't have multiple values for each query string key in this example
        
        #st.write('before', app_state)
        
        titles = [a['title']  for a in self.apps]
        functions = [a['function'] for a in self.apps]
        default_radio = titles.index(app_state["page"]) if "page" in app_state else 0

        title = st.sidebar.radio(
            'Go To',
            titles,
            index=default_radio,
            key='radio')

        app_state['page'] = st.session_state.radio
        #st.write('after', app_state)

        st.experimental_set_query_params(**app_state)
        functions[titles.index(title)]()

看起来就麻烦一些了,需要对每次的app状态参数page做一个获取,然后跳转到一个页面后及时更新这个page参数。

那还有没有更简单的操作呢?笔者看报错信息发现,在点击Foo的时候,报的是Bar这个dict不在列表里,难道是列表在点击的时候有啥变化?

那咱们在app['function']()这行之前加个print函数,打印一下self.apps看看吧。结果真的发现了问题,如下图所示。每次点击一个页面,self.apps里边的function函数在内存里边就变了,这显然是个小bug。

打印结果

那么,我们就不要这么存了就行了呀,列表里只存title,function根据点击的title去获取,问题迎刃而解。自己尝试了一种新的代码写法。

import streamlit as st

class MultiApp:
    def __init__(self):
        self.apps = []
        self.app_dict = {}

    def add_app(self, title, func):
        if title not in self.apps:
            self.apps.append(title)
            self.app_dict[title] = func

    def run(self):
        title = st.sidebar.radio(
            'Go To',
            self.apps,
            format_func=lambda title: str(title))
        self.app_dict[title]()

再去执行一下看看,结果正常,不会再报错了。

2.3 开源工具包

在谷歌上搜了下,还真有开源的工具包,streamlit-multipage。项目地址在这里,支持pip安装。
项目支持的功能比较多,除了单页面、多页面之外,还可以自定义命名空间、自定义UI等等。缺点就是,你得花时间熟悉别人的代码思路,改起来会有点费劲。其中多页面部分代码如下。

import streamlit as st
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()

3 总结

本文主要介绍了如何利用streamlit实现多个前端页面的几种方法。由易到难的介绍了改端口、封装类、引入开源包的思路。希望对大家有所帮助。

4 参考文献

  1. streamlit开发手册
  2. streamlit-multiapps
  3. Streamlit Multipage

相关文章

网友评论

      本文标题:streamlit如何实现多页面

      本文链接:https://www.haomeiwen.com/subject/kuuburtx.html