1. 用 FastAPI + SSE 搭一个流式对话服务的完整过程
给内部工具搭一个对接大模型的流式接口,SSE 比 WebSocket 轻量得多。记录了依赖选型、断线重连与超时处理。
from fastapi.responses import StreamingResponse
async def stream():
async for chunk in llm.astream(prompt):
yield f"data: {json.dumps(chunk)}\n\n"
return StreamingResponse(stream(), media_type="text/event-stream")
要点
- nginx 反代记得关闭 proxy_buffering,否则流被攒住
- 客户端心跳注释行 ": keepalive" 保活
- 用 anyio 的取消机制清理上游连接
2. 十个让我少加班的 Python 自动化脚本
从日报生成、日志聚合到批量重命名与 Excel 核对。核心思路:凡是每周做两次以上的事,都值得写脚本。
import pandas as pd
df = pd.read_excel("订单.xlsx", sheet_name=None)
merged = pd.concat(df.values(), ignore_index=True)
merged.groupby("渠道")["金额"].sum().to_csv("汇总.csv")
3. 异步爬虫的限速与重试:别把对方网站打挂
asyncio.Semaphore + 指数退避 + 指纹伪装的组合拳,以及为什么我放弃了 aiohttp 改用 httpx。
async with sem: # 并发上限
for attempt in range(3): # 指数退避
try:
r = await client.get(url)
break
except HTTPError:
await asyncio.sleep(2 ** attempt)
← 返回首页