writing-streamlit-apps
它能做什么
本技能说明如何编写在 PostHog 内部运行的 Streamlit 应用的 Python 代码,包括如何读取 PostHog 数据。适合构建数据应用、并希望其可靠运行的开发者。
适用场景
- ✓当你正在为读取 PostHog 数据的 Streamlit 应用编写 Python 代码时。
- ✓当某个 Streamlit 应用在 Streamlit 重新运行后变慢或行为异常时。
- ✓当你需要在应用的主文件旁边添加辅助文件或数据文件的时候。
技能链接
https://github.com/PostHog/posthog/blob/master/products/streamlit_apps/skills/writing-streamlit-apps/SKILL.md复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。
使用方法
最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 AI
“请帮我编写一个 Streamlit 应用的 Python 代码,用图表显示 PostHog 中每天的事件。”
每周 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
RuntimeErroron 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 withst.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 posthogdoes NOT exist in the sandbox — the module isposthog_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,
LIMITresults, 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:
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)Use
st.session_statefor 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.columnsfor side-by-side metrics,st.tabsfor alternate views,st.expanderfor detail sections;st.metricfor 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 viast.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.pyis the entry point. Via the MCP set-source flow your source ISapp.py. Helper modules and data files can ship next to it through thefiles(text) andassets(base64) maps;import utilsworks because Streamlit puts the app directory onsys.path, but the process does not run inside that directory, so open data files viaPath(__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
评论
- …
同一仓库的更多技能
depot-ci
41k帮你的智能体设置并运行 Depot CI 工作流(GitHub Actions 的替代方案),包括迁移现有工作流和读取运行日志。
depot-container-builds
41k帮你的智能体在 Depot 的远程构建器上构建 Docker 镜像,包括多平台镜像、推送到镜像仓库,以及修复构建失败。
depot-github-runners
41k帮你的智能体把 GitHub Actions 任务迁移到 Depot 托管的运行器上,选择运行器规格和标签,并排查运行器设置问题。
editing-agents-md
41k帮你的智能体判断某条规则应写入 AGENTS.md 还是 CLAUDE.md,并以不会让文件臃肿的方式写下,确保规则真正生效。