
Streamlit 前端调用 FastAPI 接口时无法获取 Cookie,根本原因是 requests.get() 默认不维护会话状态;需改用 requests.Session 或 httpx.Client 实现跨请求 Cookie 持久化。
streamlit 前端调用 fastapi 接口时无法获取 cookie,根本原因是 `requests.get()` 默认不维护会话状态;需改用 `requests.session` 或 `httpx.client` 实现跨请求 cookie 持久化。
在构建 Streamlit + FastAPI 的全栈应用时,Cookie 管理是一个常见但易被忽视的关键环节。你已在 FastAPI 后端通过 response.set_cookie(...) 正确设置了 access_token 和 refresh_token(包括 domain='localhost'、path='/'、samesite='lax' 等合理参数),但 Streamlit 中直接使用 requests.get() 发起请求时始终收不到这些 Cookie——这是因为 requests.get() 是无状态的独立请求,不会自动存储或发送上一次响应中设置的 Cookie。
✅ 正确做法:使用 requests.Session(推荐)或 httpx.Client,它们会自动管理 Cookie Jar,实现「登录 → 设置 Cookie → 后续请求自动携带」的完整会话流。
以下是在 Streamlit 中的修复示例:
import streamlit as st
import requests
# ✅ 创建持久化 Session 实例(建议作为全局变量或 st.session_state 管理)
if 'session' not in st.session_state:
st.session_state.session = requests.Session()
s = st.session_state.session
# 假设用户已登录并触发了后端 set_cookie(例如跳转前调用了 /login)
# 此处调用 /get_cookies 将自动携带之前设置的 access_token 和 refresh_token
p_uri = "http://localhost:8000/user/get_cookies"
try:
response = s.get(p_uri)
response.raise_for_status()
data = response.json()
st.write("✅ 成功获取 Token:", data)
except requests.exceptions.RequestException as e:
st.error(f"❌ 请求失败:{e}")
⚠️ 关键注意事项:
-
不要在每次调用时新建
requests.Session():Session 实例应复用(如存入st.session_state),否则 Cookie 无法累积; -
跨域限制(CORS)不影响
requests.Session:因为这是服务端(Streamlit 后端)发起的请求,非浏览器 JS 调用,不涉及浏览器同源策略; -
若改用
httpx(更现代推荐):import httpx client = httpx.Client(http2=True, follow_redirects=True) response = client.get("http://localhost:8000/user/get_cookies") -
FastAPI 端无需修改:只要 Cookie 的
domain、path、samesite配置一致(如本例均为localhost和/),Session 即可正确匹配并发送; -
调试技巧:可在 FastAPI 路由中打印
request.headers.get('cookie'),验证原始 Cookie 字符串是否到达。
总结:Cookie 是会话级状态,必须依赖有状态的 HTTP 客户端才能维持。放弃裸 requests.get(),拥抱 Session 或 Client,是打通 Streamlit 与 FastAPI Cookie 流通链路的唯一可靠方式。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!











