Location>code7788 >text

『play around withStreamlit』--fragment (of speech etc)Fragments

Popularity:468 ℃/2024-12-10 17:04:28

existStreamlit application development.FragmentsA component is a tool used to more finely control the order in which page elements are updated and displayed.

It allows developers to break down content into multiple smaller pieces that can be updated in a specific order or logic, rather than updating the entire page or all the content in a container at once.

This provides more flexibility and control for creating dynamic and interactive user interfaces.

1. Summary

Fragmentsa bit likeWeb2.0currentAjaxtechnology, which is able to break up page content into smaller pieces, like dividing a complete picture into many small puzzle pieces.

The advantage of this is thatFragments The update operation can be subdivided to update only part of the content to improve page responsiveness.

Essentially, it provides developers with greater flexibility and precise content control when building dynamic, interactive application interfaces.

FragmentsThe component does not have many parameters and is generally used through thedecorator to write small snippets, which will be demonstrated later with examples.

name (of a thing) typology clarification
func function object function that converts it to a fragment.@Functions decorated by the decorator
run_every Integer, Floating Point, Interval, String or None None(default): segments are re-run only when the user triggers an event.
Integer or floating point number: Specify a time interval in seconds, e.g. 5 means that the clip is automatically re-run every 5 seconds.
string (computer science): Specify a time format such as "1d" (1 day), "1.5 days" (1.5 days), or "1h23s" (1 hour 23 seconds), which is supported by Pandas' Timedelta constructor.
timedelta object(from Python's built-in datetime library): e.g. timedelta(days=1) means to re-run the fragment automatically every day.

2. Fragments and Forms

Fragmentsand the previous one introducedFormIt looks similar in that it's all about organizing multiple associated components and updating and managing them in a unified way.

In fact, their application scenarios and ways of working are very different, and understanding the differences will allow us to better select the appropriate components.

2.1 Main uses

surname Conguseviewed from the top.FragmentsMainly for:

  • Enabling Guided Content Presentation: Used to create guided application interfaces to present information step-by-step. For example, in a tutorial for a data analytics app, start by using theFragmentsDemonstrate the steps of data loading, followed by an introduction to data analysis methods.
  • Optimize page update performance: when dealing with large amounts of data or complex UI updates.FragmentsIt is possible to split the update operation into multiple small segment updates. Refreshing only the necessary parts at a time improves the responsiveness of the application. For example, in a real-time data monitoring application using theFragmentsSections of different data charts can be updated separately, rather than updating all charts on the entire page at once.
  • Building Complex Interaction Logic: For applications with complex interaction logic, theFragmentsCan help organize and control the showing and hiding of page elements. For example, in a multi-step action flow application, byFragmentsManage the showing and hiding of different action buttons and prompt messages in each step.

(indicates contrast)FormInstead, it is mainly used:

  • Data collection: Mainly used to collect data entered by the user. This can be simple textual information or complex choices, such as in a product configuration form where the user selects options such as product model, color, etc. via drop-down menus.
  • Data validation and submission: Forms often include data validation mechanisms to ensure that the data entered by the user meets the requirements. And, forms provideSubmission FunctionsThe collected user data is sent to the server or processed locally.

2.2 Modus operandi

From the component'sworking methodCome and see.Fragmentsitself does not have a fixed structure like a form.

It is more like a container for a variety ofStreamlit components such as text, buttons, charts, etc. Code logic can be used to control these components in theFragmentsThe display order and conditions in the

(indicates contrast)form (document)has a relatively clear structure and usually containsformtags (at the HTML level) and a series of input components such as thest.text_inputetc.

All input components in a form are usually interrelated and together they form a data collection unit.

Moreover, forms can be passed through thest.form_submit_buttonto trigger a commit operation, and you can use thecontext manager to ensure that component data within a form is processed together correctly when submitted.

2.3 Data processing

existdata processingAspects.FragmentsRelatively flexible, e.g., in the case of a system containing more than oneFragmentsin the application of the

everyonefragmentMay have its own separate button, click on the button after the both can update the currentfragmentThe otherfragmentThe update.

Data interactions are more visible in differentfragmentswitching between and on content updates.

(indicates contrast)FormWhere data processing is centered around user input, operations such as validation, cleansing, and storage of the collected data are usually performed after the form has been submitted.

For example, the registration information entered by the user in the form is sent to a database for storage, or the data is retrieved from the database and displayed according to the query conditions selected by the user in the form.

The interaction within the form is mainly focused on user input and submission operations, as well as giving the user appropriate feedback based on the legitimacy of the input data, such as prompting the input error message.

3. Fragments use examples

This is demonstrated below with two examples simplified for real-world situationsFragmentsThe usage scenarios.

3.1 Progressive display of information

In this example, we have created a product introduction page, which is accessed via theFragmentsThe component displays the information in three progressive steps.

The welcome message is displayed first, and when the user clicks 【Click to learn more] button after which the product function information is displayed.

Then click [Continue to the next step.] button after displaying the product advantage information.

import streamlit as st

def step1()
def step1().
    ("Welcome to our product page.")
    if ("Click to learn more", key="step1")::("Welcome to our product introduction page.")
        step2()


@
def step2().
    ("These are the main features of our product: feature 1, feature 2, and feature 3.")
    if ("Continue to the next step", key="step2")::
        step3()


@
def step3().
    ("Finally, this is where our product excels, such as efficiency and ease of use.")
    if ("refresh", key="step3"):.
        ()


# Initially display the first clip
step1()

3.2 Localized page refreshes

This example simulates a large data display screen, which is divided into two columns, each displaying theSales datarespond in singingTraffic data

Each data area has its own refresh button, and when the button is clicked, it only re-runs the correspondingfragment function, thus enabling a localized refresh of the data in that area without affecting the rest.

import streamlit as st
import random


# Simulate getting some data
def get_sales_data(): return (100, 1000)
    return (100, 1000)


def get_traffic_data(): return (50, 500)
    return (50, 500)


# Create a sales data display snippet
@
def sales_data_fragment().
    ("sales_data")
    # Get and display sales data
    sales_data = get_sales_data()
    (f "Today's sales: {sales_data}")
    # Refresh sales data locally
    if ("Refresh sales data", key="sales"): if ("Refresh sales data", key="sales"): if ("Refresh sales data", key="sales").
        (scope="fragment")


# Create the traffic data display fragment
@
def traffic_data_fragment().
    ("traffic_data")
    # Get and display traffic data
    traffic_data = get_traffic_data()
    (f "Today's traffic: {traffic_data}")
    # Refresh traffic data locally
    
        (scope="fragment")


# Main function, arranging the fragments on the big screen
def main().
    # Split the screen into two columns for each fragment
    col1, col2 = (2)
    with col1.
        sales_data_fragment()
    with col2:
        traffic_data_fragment()


if __name__ == "__main__".
    main()

4. Summary

Finally, summarize when you should be able to consider choosing aFragmentsto build ourstreamlitApplications.

First, it is necessary toStep-by-step information displayWhen you do, consider using theFragments

For example, when creating a tutorial or guided application interface, display a portion of the explanatory text first, and then display the next step after the user performs a certain operation (e.g., clicking a button), instead of presenting all the tutorial information to the user at once, to avoid information overload, which affects the user's understanding and operation experience.

Secondly.Optimize page update performanceWhen you do, consider using theFragments

For example, when there is a lot of data in the application or complex UI updates, theFragmentsThe component can split the update operation into multiple small snippet updates. In this way, only the necessary parts are refreshed during each update, reducing the amount of work involved in re-rendering the page and thus improving the responsiveness and performance of the application.

there areBuilding Complex Interaction LogicYou may also want to consider using theFragments

When building applications with complex interaction logic, theFragmentsComponents help developers better organize and control the display and hiding of page elements.