본문으로 건너뛰기
Skillpedia
웹사이트 및 UI (프런트엔드)41k · #6955

writing-streamlit-apps

하는 일

이 스킬은 PostHog 안에서 실행되는 Streamlit 앱의 Python 코드를 작성하는 방법을 설명합니다. PostHog 데이터를 읽는 방법도 포함합니다. 데이터 앱을 만들고 안정적으로 작동하기를 원하는 개발자를 위한 스킬입니다.

사용하는 경우

  • ✓PostHog 데이터를 읽는 Streamlit 앱의 Python 코드를 작성할 때.
  • ✓Streamlit이 다시 실행된 뒤 앱이 느리거나 이상하게 작동할 때.
  • ✓앱의 메인 파일 옆에 도우미 파일이나 데이터 파일을 추가해야 할 때.

스킬 링크

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

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/PostHog/posthog/blob/master/products/streamlit_apps/skills/writing-streamlit-apps/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“일별 이벤트를 PostHog에서 가져와 차트로 보여 주는 Streamlit 앱의 Python 코드를 도와주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

PostHog 데이터를 표로 읽어 오는 내장 방법, 샌드박스에 이미 있는 라이브러리, 캐싱과 상태 관리 패턴을 보여 줍니다. 또 도우미 모듈과 데이터 파일을 메인 앱 파일 옆에 추가하는 방법도 설명합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

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
자주 묻는 질문

앱은 PostHog 데이터를 어떻게 읽나요?

표를 반환하는 내장 쿼리 함수를 쓰므로, 앱이 로그인 정보를 직접 다루지 않습니다.

왜 일반 PostHog 라이브러리를 가져올 수 없나요?

샌드박스는 데이터 접근을 위해 자체 모듈을 쓰므로, 일반 PostHog 라이브러리는 그곳에서 쓸 수 없습니다.

쿼리에 제한이 있나요?

네. 쿼리에는 시간과 메모리 상한이 있으므로, 시간 범위를 제한하고 결과 수를 줄이라고 권장합니다.

상세 정보

작성자의 원본 설명

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

인기도

GitHub 스타
41k
순위
#6955
라이선스
—
업데이트
2026. 11. 2.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬