πŸ“Š Data Engineering

Streamlit

Streamlit

A Python data app framework. Rapid prototyping.

Detailed Explanation

Streamlit is an open-source data app framework for Python developers. Without complex front-end knowledge, you can build interactive web applications in just a few minutes using only pure Python code.

Key features

  • Simple API: Build the UI with intuitive functions such as st.write() and st.dataframe()
  • Hot Reload: The app refreshes automatically when you save the code
  • Widget System: A rich set of input widgets such as st.slider(), st.selectbox(), and st.button()
  • Caching: Performance optimization with @st.cache_data and @st.cache_resource
  • State Management: Manage user session state with st.session_state

Key Components

  • Display Elements: st.write, st.markdown, st.latex, st.code
  • Data Elements: st.dataframe, st.table, st.metric, st.json
  • Chart Elements: st.line_chart, st.bar_chart, st.pyplot, st.plotly_chart
  • Input Widgets: st.text_input, st.number_input, st.date_input, st.file_uploader
  • Layout: st.sidebar, st.columns, st.expander, st.tabs, st.container

Streamlit Cloud

Through Streamlit Cloud, one-click deployment is possible via GitHub integration, and Community Cloud hosts public apps for free. Data scientists can quickly share ML model demos, dashboards, and data exploration tools.

Code Example

Basic Data App Structure

# app.py
import streamlit as st
import pandas as pd
import numpy as np

# νŽ˜μ΄μ§€ μ„€μ •
st.set_page_config(
    page_title="데이터 λŒ€μ‹œλ³΄λ“œ",
    page_icon="πŸ“Š",
    layout="wide",
    initial_sidebar_state="expanded"
)

# 제λͺ©κ³Ό μ„€λͺ…
st.title("πŸ“Š 데이터 뢄석 λŒ€μ‹œλ³΄λ“œ")
st.markdown("""
이 λŒ€μ‹œλ³΄λ“œλŠ” **μ‹€μ‹œκ°„ 데이터 뢄석**을 μœ„ν•œ μΈν„°λž™ν‹°λΈŒ λ„κ΅¬μž…λ‹ˆλ‹€.
μ‚¬μ΄λ“œλ°”μ—μ„œ μ˜΅μ…˜μ„ μ‘°μ ˆν•΄ λ³΄μ„Έμš”!
""")

# μ‚¬μ΄λ“œλ°” μ„€μ •
st.sidebar.header("μ„€μ •")
data_size = st.sidebar.slider("데이터 크기", 100, 1000, 500)
chart_type = st.sidebar.selectbox("차트 νƒ€μž…", ["Line", "Bar", "Area"])

# μƒ˜ν”Œ 데이터 생성
@st.cache_data
def generate_data(size):
    dates = pd.date_range(start="2024-01-01", periods=size)
    return pd.DataFrame({
        "λ‚ μ§œ": dates,
        "맀좜": np.random.randint(1000, 5000, size),
        "λΉ„μš©": np.random.randint(500, 2000, size),
        "이읡": np.random.randint(200, 1500, size)
    })

df = generate_data(data_size)

# λ©”νŠΈλ¦­ ν‘œμ‹œ
col1, col2, col3 = st.columns(3)
with col1:
    st.metric("총 맀좜", f"${df['맀좜'].sum():,.0f}", "+12%")
with col2:
    st.metric("평균 λΉ„μš©", f"${df['λΉ„μš©'].mean():,.0f}", "-5%")
with col3:
    st.metric("순이읡", f"${df['이읡'].sum():,.0f}", "+8%")

# 차트 ν‘œμ‹œ
st.subheader(f"{chart_type} 차트")
chart_data = df.set_index("λ‚ μ§œ")[["맀좜", "λΉ„μš©"]]

if chart_type == "Line":
    st.line_chart(chart_data)
elif chart_type == "Bar":
    st.bar_chart(chart_data)
else:
    st.area_chart(chart_data)

# 데이터 ν…Œμ΄λΈ” (ν™•μž₯ κ°€λŠ₯)
with st.expander("πŸ“‹ 상세 데이터 보기"):
    st.dataframe(df, use_container_width=True)

Session State and Callbacks

import streamlit as st

# Session State μ΄ˆκΈ°ν™”
if "counter" not in st.session_state:
    st.session_state.counter = 0
if "messages" not in st.session_state:
    st.session_state.messages = []

# 콜백 ν•¨μˆ˜
def increment_counter():
    st.session_state.counter += 1

def add_message():
    if st.session_state.new_message:
        st.session_state.messages.append(st.session_state.new_message)
        st.session_state.new_message = ""  # μž…λ ₯ ν•„λ“œ μ΄ˆκΈ°ν™”

# UI
st.header("Session State 데λͺ¨")

# μΉ΄μš΄ν„°
col1, col2 = st.columns(2)
with col1:
    st.button("μΉ΄μš΄ν„° 증가", on_click=increment_counter)
    st.write(f"ν˜„μž¬ μΉ΄μš΄ν„°: {st.session_state.counter}")

# λ©”μ‹œμ§€ 리슀트
with col2:
    st.text_input("λ©”μ‹œμ§€ μΆ”κ°€", key="new_message", on_change=add_message)
    for i, msg in enumerate(st.session_state.messages):
        st.write(f"{i+1}. {msg}")

File Upload and ML Model Demo

import streamlit as st
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split

st.title("πŸ€– ML λͺ¨λΈ 데λͺ¨")

# 파일 μ—…λ‘œλ“œ
uploaded_file = st.file_uploader("CSV νŒŒμΌμ„ μ—…λ‘œλ“œν•˜μ„Έμš”", type=["csv"])

if uploaded_file is not None:
    df = pd.read_csv(uploaded_file)

    st.subheader("데이터 미리보기")
    st.dataframe(df.head())

    # 컬럼 선택
    st.subheader("λͺ¨λΈ μ„€μ •")
    target_col = st.selectbox("νƒ€κ²Ÿ 컬럼", df.columns)
    feature_cols = st.multiselect(
        "ν”Όμ²˜ 컬럼",
        [c for c in df.columns if c != target_col]
    )

    if feature_cols and st.button("λͺ¨λΈ ν•™μŠ΅"):
        with st.spinner("λͺ¨λΈ ν•™μŠ΅ 쀑..."):
            X = df[feature_cols]
            y = df[target_col]
            X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

            model = RandomForestClassifier(n_estimators=100)
            model.fit(X_train, y_train)

            accuracy = model.score(X_test, y_test)

        st.success(f"λͺ¨λΈ ν•™μŠ΅ μ™„λ£Œ! 정확도: {accuracy:.2%}")

        # ν”Όμ²˜ μ€‘μš”λ„
        importance_df = pd.DataFrame({
            "Feature": feature_cols,
            "Importance": model.feature_importances_
        }).sort_values("Importance", ascending=False)

        st.bar_chart(importance_df.set_index("Feature"))

Multi-page App Structure

# 디렉토리 ꡬ쑰
# my_app/
# β”œβ”€β”€ Home.py           # 메인 νŽ˜μ΄μ§€ (streamlit run Home.py)
# └── pages/
#     β”œβ”€β”€ 1_πŸ“Š_Data.py  # 첫 번째 νŽ˜μ΄μ§€
#     β”œβ”€β”€ 2_πŸ“ˆ_Charts.py # 두 번째 νŽ˜μ΄μ§€
#     └── 3_βš™οΈ_Settings.py

# Home.py
import streamlit as st

st.set_page_config(page_title="λ©€ν‹° νŽ˜μ΄μ§€ μ•±", page_icon="🏠")

st.title("🏠 ν™ˆνŽ˜μ΄μ§€")
st.markdown("""
μ‚¬μ΄λ“œλ°”μ—μ„œ λ‹€λ₯Έ νŽ˜μ΄μ§€λ‘œ 이동할 수 μžˆμŠ΅λ‹ˆλ‹€.
- πŸ“Š Data: 데이터 뢄석
- πŸ“ˆ Charts: μ‹œκ°ν™”
- βš™οΈ Settings: μ„€μ •
""")

# pages/1_πŸ“Š_Data.py
import streamlit as st
import pandas as pd

st.title("πŸ“Š 데이터 뢄석")
# νŽ˜μ΄μ§€λ³„ 컨텐츠...

Practical Conversation Example

Meeting: Discussing a Data App Prototype

PM:
"We need an interface that non-developers can also use to easily check the ML model results. Should we make a request to the web development team?"
Data Scientist:
"We can build it quickly with Streamlit. The UI can be built with Python alone, and we can even make it ourselves within this week."
PM:
"Do we not need front-end experience?"
Data Scientist:
"Right, adjusting parameters with st.slider(), displaying tables with st.dataframe(), and even charts with st.plotly_chart() are all done with just Python function calls. Deployment is also automatic if you connect GitHub to Streamlit Cloud."

Interview: Experience Using Streamlit

Interviewer:
"Do you have experience developing data apps?"
Candidate:
"I built a real-time model inference dashboard with Streamlit. I cached the model with @st.cache_resource so it isn't loaded on every request, and I managed each user's input history with st.session_state."
Interviewer:
"Were there any performance issues?"
Candidate:
"I cached data preprocessing results with @st.cache_data, and for large datasets I used the pagination feature of st.dataframe. For heavy computations, I improved the UX by showing a loading state with st.spinner()."

Code Review: Optimizing a Streamlit App

Senior:
"Looking at this code, it re-reads the CSV every time the page loads. Please add the @st.cache_data decorator."
Junior:
"Do we need to set a TTL as well?"
Senior:
"Yes, it would be good to refresh it every hour with @st.cache_data(ttl=3600). Also, if you split the column layout with st.columns(), screen utilization will improve."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

Cautions

Stateless Architecture

Streamlit re-runs the entire script on every interaction. If you do not use session_state, state is not preserved, so be sure to store user input and calculation results in st.session_state.

Distinguishing Caching Decorators

Use @st.cache_data for serializable data (DataFrame, dict) and @st.cache_resource for non-serializable objects (ML models, DB connections). If used incorrectly, errors occur or caching does not work properly.

Concurrent User Limits

Because Streamlit runs single-threaded, performance degrades when there are many concurrent users. In a production environment, run multiple instances or check the limits of Streamlit Community Cloud.

Duplicate Widget Keys

When creating widgets inside a loop, you must specify a unique key parameter. If the key is duplicated, a "DuplicateWidgetID" error occurs.

Security Considerations

Use st.secrets to manage API keys and sensitive information. Be careful not to hard-code them directly in the code or commit .env files, and add secrets.toml to .gitignore.

Related Terms

Learn More

Official Documentation

Streamlit Documentation

Provides API reference, tutorials, and guides

docs.streamlit.io
Gallery

Streamlit Gallery

A collection of various Streamlit app examples

streamlit.io/gallery
Community

Streamlit Forum

A community for questions, discussions, and showcases

discuss.streamlit.io
Deployment

Streamlit Community Cloud

A platform for free app hosting and deployment

streamlit.io/cloud