from typing import Annotated
from fastapi import Cookie, FastAPI, Header
from fastapi.responses import JSONResponse
app=FastAPI(title="蓝色天空网请求上下文",docs_url=None,redoc_url=None)
@app.get("/context")
def context(user_agent: Annotated[str | None, Header()] = None,
x_station: Annotated[list[str] | None, Header()] = None,
content_type: Annotated[str | None, Header()] = None,
station_session: Annotated[str | None, Cookie()] = None,
view_mode: Annotated[str | None, Cookie()] = None):
return {"user_agent":user_agent,"station_headers":x_station,"content_type":content_type,
"station_session":station_session,"view_mode":view_mode}
@app.get("/literal")
def literal(x_station: Annotated[str | None, Header(convert_underscores=False)] = None):
return {"header":x_station}
@app.get("/restricted-values")
def restricted(x_zone: Annotated[str, Header(min_length=3)],
view_mode: Annotated[str, Cookie(pattern=r"^(compact|wide)$")]):
return {"zone":x_zone,"view_mode":view_mode}
@app.get("/cookie-set")
def cookies():
response=JSONResponse({"fixture":"two browser cookies"})
response.set_cookie("station_session","session-lab",path="/context",httponly=True,samesite="lax")
response.set_cookie("view_mode","compact",path="/",samesite="lax")
return response
@app.get("/other")
def other(station_session: Annotated[str | None, Cookie()] = None,
view_mode: Annotated[str | None, Cookie()] = None):
return {"station_session":station_session,"view_mode":view_mode}
本例需在 CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0
入口文件:projects/fastapi-header-cookie-lab/main.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
main.py,或下载右侧课程工程包。 - 确认本地已准备 CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202611a503.zip
课程关联工程包(登记关联38章) · 含当前章节或实例 · mbskycom202612a182.zip