Improving Streamlit App with Fragments

Streamlit是一个Python库,旨在快速轻松地创建数据驱动的应用程序,最近越来越受欢迎. According to Google Trends, 现在关于Streamlit的谷歌搜索比Streamlit历史上任何时候都要多. Not only is it popular now, 但趋势显示,streamlight的使用每年都呈指数级增长. With the immense growth in its popularity, there has never been a better time to start learning Streamlit. Luckily for developers who may have missed out until now, Streamlit’s API is intuitive and mostly well-documented. 然而,在Streamlit中有一些东西是很难理解的. One of the most obvious examples is 片段s. Fragments是开发人员定义Streamlit程序的一种方式,它可以独立于页面的其余部分重新加载. This behavior is very powerful but can also be very confusing. This article will discuss how Streamlit works without 片段s, how this behavior changes with the addition of 片段s, and how a developer can start using 片段s in their Streamlit apps.

回来ground

Let’s start by examining how Streamlit works without 片段s. 在一个正常的流光应用程序, all the python code you’ve written is executed sequentially, 从上到下. When a user interacts with a widget on the page, or st.rerun() is called, the entire page is queued to be reloaded 从上到下. If a widget is used to set a variable, 在重新运行之前,该变量不会获取其小部件的值.  

http://moser-blog-fragment-example-1.streamlit.app/

图片显示了一条线在流光代码上,显示了流光代码通常是如何运行的.

动机

Streamlit’s default behavior works well in most cases. 然而, 在某些情况下,对小部件的每次更新都重新运行整个页面对于程序的目的来说可能太慢或效率太低. 以下是Streamlit中由于默认行为而难以创建或使用的一些示例.  

动态形式

在Streamlit中,表单批处理小部件输入,以便与单个按钮同步. 这提供了一种让用户输入一系列条目而不触发多次页面重新运行的方法, saving both the user’s time and processing power. 然而, forms are not dynamic; the values stored in the widgets before the form submit button is pressed cannot be read. This means that it is impossible to have live input validation, 例如,锁定提交按钮,直到填写完表单中所有必需的字段.

http://moser-blog-app-example-dynamic-form.streamlit.app/

一个Streamlit程序,它显示了两个表单:一个是静态表单,只在用户提交后验证用户输入, leading to a poor user experience, 另一个表单在用户的表单输入有效时动态启用提交按钮, leading to a better user experience

图形

            图形 are a great way to display information, Streamlit提供了许多方法来创建各种图形和图表来解释你的数据. 然而, 每次页面运行生成多个图形可能会相当费力,并且会大大降低应用程序的速度. It is possible to cache graphs to only generate them once, but in situations where the data being displayed could change, or where the graph needs to adapt to user input, caching will not solve the problem.

数据流

            有时, 应用程序需要不断获取数据,以便为用户提供尽可能最新的信息. Streamlit provides a way to cache database results for a set amount of time, but there is no method of forcing the page to use these updated values automatically; a page rerun must be triggered to update the data. A potential solution is to use time.sleep() to trigger reruns on fixed intervals, but this will cause the entire page to rerun just to refresh data. 如果mg官方游戏中心能将这个重新运行的范围限定为只影响需要重新加载的数据,那就太好了, but with default Streamlit behavior, 似乎不可能.

输入的片段

Fragments通过定义特定的函数来改变Streamlit的默认行为,这些函数可以独立于页面的其余部分重新运行. 这意味着应用中需要不断反映新数据的部分可能会以固定的速率重新加载, 或者应用程序中需要大量用户输入的部分可以与页面的其余部分分开,以增加加载时间. 虽然片段有很多好处,但如果配置不当,它们也会导致奇怪的行为. 让mg官方游戏中心来看看Streamlit将如何处理带有片段的程序的不同区域中的用户输入.

里面的片段

当从片段内部触发重新运行时,该片段将排队等待重新运行. Any normal Python variables defined inside the 片段 are reset, and session state variables are updated. The widgets outside the 片段 will not be updated, even if session state variables assigning their properties are changed.

外面的片段

当从片段外部触发重新运行时,整个页面将正常重新运行. 所有python变量被重置,会话状态变量的值被更新. A 片段 is not protected from updates in the rest of the page. A 片段 only protects the rest of the page from updates within itself.  

http://moser-blog-fragment-example-3.streamlit.app/

一个流灯光应用程序,展示了在包含片段的流灯光应用程序的不同部分触发重播如何影响应用程序的其余部分.

定义片段

You can define a 片段 in your code by using the decorator @st.experimental_片段. This decorator takes one parameter: run_every. 该参数默认为None,用于定义片段自动重新加载的时间间隔. This is used for streaming data from a database, API, or some other data storage. " run_every "可以是Int或Float类型,表示两次运行之间的秒数, 一个字符串,可以转换为带有Pandas的Timedelta对象,如“2h”或“3天”。, 或Timedelta对象. When run_every is none, the 片段 will never automatically refresh; only a user input or a st.rerun() call will refresh the 片段.

@st.experimental_片段(run_every=5)
def random_number_片段 ():
    st.write("This code will be rerun every 5 seconds!")

    st.button("Click to manualy trigger a reload!")

    st.metric("Latest random number", random.randint (0, 99))

random_number_片段 ()

结论

到目前为止,您应该更清楚地掌握了片段在Streamlit中的操作方式. We've walked through how Streamlit works without 片段s, how adding 片段s alters its behavior, and how to define 片段s within your Streamlit projects. 有了这些知识, 你现在有更好的装备来提升你的流光技能和工艺迷人, 交互式应用程序. Whether you're a seasoned developer or just starting out, 将片段集成到Streamlit工具包中,为创建动态和引人入胜的用户体验开辟了令人兴奋的可能性. 所以,继续,实验,并把你的想法与流光的多功能功能的生活!

到现在为止, 很明显,片段s允许开发者增强Streamlit的正常功能,并创建更复杂的应用程序. 没有片段s,复杂的Streamlit应用程序可能会遇到问题,变得缓慢或不可用. Fragments allow these advanced programs to be developed quicker, 跑得更快, and perform better than would otherwise be possible. While 片段s can lead to unexpected behavior with Session States at first, the interaction is easy to understand at a second glance. Fragments enable developers to harness Streamlit's full potential, ensuring developers’ applications achieve optimal performance and functionality.

更新:7/29/2024

With the release of Streamlit 1.2024年7月25日,碎片发生了变化,不再是一个实验特征. As such, the syntax to define a 片段 has changed.

旧的语法

@st.experimental_片段(run_every =“4 s”)
def this_is_a_片段 ():
    st.write("This is inside of a 片段!")

新语法

@st.片段(run_every =“4 s”)
def this_is_a_片段 ():
    st.write("This is inside of a 片段!")

The greatest change is that the decorator “@st.experimental_片段” has been replaced with “@st.片段”. 旧的实验装饰器已弃用,将于2025年1月1日拆除. Another important change is that “st.通过将关键字参数“scope”设置为“片段”,现在可以将“Rerun”的作用域限定为只重新运行它内部的片段。. 这将使重新运行片段变得更加简单,而无需重新运行整个页面.

st.rerun(scope="片段") # This will only rerun the 片段 it is inside
st.rerun() # This will rerun the entire app

Fragments still have the same functionality as when this article was written. The background and purpose of 片段s have not changed. Fragments are even more useful now than they were before.

Links to Other Moser Webpages

http://07fq.shadleysoapstone.com/blog/creating-a-web-app-with-snowflake-and-streamlit

参考文献

包括文章中引用的Moser网站以外的任何链接:

http://trends.谷歌.com/trends/explore?日期=所有&q = streamlit&hl = en

http://docs.streamlit.io/develop/api-reference/execution-flow/st.fragment

http://docs.streamlit.io/develop/concepts/architecture/fragments

接触莫泽 today for your company’s technology needs.

伊桑Poorbaugh

伊桑Poorbaugh is a Data Engineering Intern at MG游戏登录网页. His attends Anderson University where he majors in Data Science. Ethan has experience in big data technologies such as PostgreSQL, 雪花, and Python and is ready to gain more experience in the field.

以前的
以前的

Using AI to Transform Every Team in Your Organization

下一个
下一个

The Crucial Role of Data Visualization