import os
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
api=FastAPI()
activity={"post":0,"simple":0}
front=os.environ.get("MBSKY_FRONT_ORIGIN","http://127.0.0.1:8011")
@api.get("/cookie")
def cookie():
response=JSONResponse({"cookie":"fixture only"})
response.set_cookie("lab_view","compact",path="/cors",samesite="lax",httponly=True)
return response
@api.post("/value")
async def value(request: Request):
activity["post"]+=1
return JSONResponse({"value":(await request.json())["value"],"cookie":request.cookies.get("lab_view"),
"tag":request.headers.get("x-lab-tag")},
headers={"X-Lab-Result":"public","X-Internal":"synthetic"})
@api.get("/simple")
def simple():
activity["simple"]+=1
return {"readable":True}
@api.get("/counts")
def counts():
return activity
@api.post("/simple")
async def simple_post(request: Request):
return {"content_type":request.headers.get("content-type"),"bytes":len(await request.body())}
public_api=FastAPI()
@public_api.get("/sample")
def public_sample():
return {"public":True}
public_demo=CORSMiddleware(public_api,allow_origins=["*"],allow_credentials=False,
allow_methods=["GET"],allow_headers=[])
protected=CORSMiddleware(api,allow_origins=[front],allow_credentials=True,
allow_methods=["GET","POST","PUT","DELETE"],allow_headers=["X-Lab-Tag","Content-Type","Authorization"],
expose_headers=["X-Lab-Result"],max_age=120)
本例需在 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-web-behavior-lab/cors_lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
cors_lab.py,或下载右侧课程工程包。 - 确认本地已准备 CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联4章) · 含当前章节或实例 · mbskycom202611a512.zip
课程关联工程包(登记关联38章) · 含当前章节或实例 · mbskycom202612a182.zip