Chuyển đến nội dung
Skillpedia
Website và giao diện (frontend)41k · #6955

writing-streamlit-apps

Skill này làm gì

Skill này giải thích cách viết mã Python của một ứng dụng Streamlit chạy trong PostHog, bao gồm cách đọc dữ liệu PostHog. Skill dành cho lập trình viên xây ứng dụng dữ liệu và muốn chúng hoạt động ổn định.

Khi nào nên dùng

  • ✓Khi bạn đang viết mã Python cho một ứng dụng Streamlit đọc dữ liệu PostHog.
  • ✓Khi một ứng dụng Streamlit chậm hoặc hoạt động sai sau khi Streamlit chạy lại.
  • ✓Khi bạn cần thêm tệp trợ giúp hoặc tệp dữ liệu cạnh tệp chính của ứng dụng.

Liên kết skill

https://github.com/PostHog/posthog/blob/master/products/streamlit_apps/skills/writing-streamlit-apps/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/PostHog/posthog/blob/master/products/streamlit_apps/skills/writing-streamlit-apps/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Giúp tôi viết mã Python cho một ứng dụng Streamlit vẽ biểu đồ sự kiện hằng ngày từ PostHog.”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Skill chỉ cách đọc dữ liệu PostHog vào một bảng bằng cách tích hợp sẵn, các thư viện đã có sẵn trong sandbox, và các mẫu cho bộ nhớ đệm và trạng thái. Skill cũng giải thích cách thêm module hỗ trợ và tệp dữ liệu cạnh tệp chính của ứng dụng.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

Writing Streamlit apps for the PostHog sandbox

The source you write becomes app.py at the root of a sandboxed Streamlit 1.31 runtime. Deployment mechanics (create/start/share) are the managing-streamlit-apps skill; this one is about the code.

Reading PostHog data: posthog_apps.query()

The one and only data door is the in-sandbox bridge:

import posthog_apps

df = posthog_apps.query("SELECT event, count() FROM events GROUP BY event LIMIT 10")
  • Takes a HogQL string, returns a pandas DataFrame.
  • Raises RuntimeError on failure. The message is deliberately generic ("Query execution failed") — the bridge does not return query internals to the sandbox, so you cannot diagnose a bad query from inside the app. Catch it and render with st.error(str(e)) so viewers get a message instead of a stack trace, and test queries in the SQL editor where real errors are visible.
  • import posthog does NOT exist in the sandbox — the module is posthog_apps, deliberately distinct from the posthog-python SDK's name.
  • The bridge is pre-authenticated to the app's project; user code never sees a token, and there is nothing to configure.
  • Queries run with server-side caps (30 s execution, 256 MB memory) that don't scale with sandbox sizing — so bound time ranges, LIMIT results, and aggregate in HogQL rather than pulling raw events into pandas.

Design for Streamlit's rerun model

Streamlit reruns the whole script top to bottom on every widget interaction. Two consequences:

  1. Cache every bridge call — uncached, one slider drag re-fires every query:

    @st.cache_data(ttl=300, show_spinner="Running query...")
    def run_query(hogql: str) -> pd.DataFrame:
        return posthog_apps.query(hogql)
    
  2. Use st.session_state for anything that must survive reruns — accumulated selections, pagination cursors, "last refreshed" stamps. Module-level variables reset on every interaction.

Widgets drive parameters naturally, but never interpolate a free-text widget value into HogQL. The bridge runs your query with the version author's data access, and anyone who can view the app drives those widgets — a raw st.text_input spliced into a query hands viewers the author's access to write their own. Constrain the input instead: pick from a fixed list you control (st.selectbox over known values), or coerce to a type that can't carry SQL (int(days), a date from st.date_input), and validate before it reaches the query.

Layout and charts

  • st.set_page_config(page_title=..., layout="wide") first — the default narrow layout wastes most of the screen for data apps.
  • Structure with st.columns for side-by-side metrics, st.tabs for alternate views, st.expander for detail sections; st.metric for headline numbers.
  • Charts: st.plotly_chart(fig, use_container_width=True) with plotly express is the reliable default; st.dataframe(df, use_container_width=True) for tables. matplotlib/seaborn also work via st.pyplot.

What's installed

The image ships Python 3.11 with: streamlit 1.31, pandas, numpy, polars, plotly, matplotlib, seaborn, scipy, scikit-learn, pyarrow, duckdb, requests, beautifulsoup4, lxml, sqlalchemy, aiohttp. There is no way to add dependencies: the sandbox never runs pip (a deliberate security posture — no arbitrary package code at boot), and a requirements.txt in an uploaded zip is tolerated but dropped. Only import what's listed above.

Structure and runtime constraints

  • app.py is the entry point. Via the MCP set-source flow your source IS app.py. Helper modules and data files can ship next to it through the files (text) and assets (base64) maps; import utils works because Streamlit puts the app directory on sys.path, but the process does not run inside that directory, so open data files via Path(__file__).parent / "data/events.parquet", never a bare relative path. Keep bundled data small: it is sent inline as JSON on every set-source call.
  • The sandbox is ephemeral: anything written to disk disappears on stop/restart. Don't build state on files; recompute from queries (with caching) or hold it in st.session_state.
  • Your code runs as an unprivileged user; there's no posthog SDK, no way to pass your own environment variables or secrets to the app, and no expectation of general network egress. Don't read from os.environ — anything there belongs to the sandbox runtime, not your app. Design
Câu hỏi thường gặp

Ứng dụng đọc dữ liệu PostHog bằng cách nào?

Nó dùng một hàm truy vấn tích hợp sẵn trả về một bảng, nên ứng dụng không bao giờ xử lý thông tin đăng nhập.

Vì sao tôi không thể import thư viện PostHog thông thường?

Sandbox dùng một module riêng để truy cập dữ liệu, nên thư viện PostHog thông thường không có sẵn ở đó.

Có giới hạn nào với truy vấn không?

Có. Truy vấn có giới hạn thời gian và bộ nhớ, nên skill khuyên nên giới hạn khoảng thời gian và số kết quả.

Chi tiết

Mô tả gốc của tác giả

Write Streamlit app source code that runs well in a PostHog sandbox — the posthog_apps.query() bridge for reading PostHog data, the packages baked into the sandbox image, caching and session state across Streamlit reruns, layout and chart patterns, and the app.py entry point with any helper modules and data files bundled beside it. Use when authoring or debugging the Python source of a PostHog Streamlit app, when a query inside an app fails, or when asked to "write a streamlit app that shows PostHog data".

repo: PostHog/posthog

Độ phổ biến

Sao GitHub
41k
Vị trí xếp hạng
#6955
Giấy phép
—
Cập nhật
2/11/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự