中间件与CORS(基于fastapi)

中间件与CORS

中间件

中间件是一个函数,它在每个请求被特定路径操作处理之前,以及每个响应之后操作。

简单来说,中间件可以看作是请求和响应之间的一个处理层,可以用来实现一些通用的功能,比如日志记录、身份验证、请求修改等。

python 复制代码
from fastapi import FastAPI,Request, Response
import time
import uvicorn

app = FastAPI()

@app.middleware("http")
async def m2(request:Request, call_next):
    #请求代码块
    print("中间件m2被调用")
    response = await call_next(request)
    #响应代码块
    response.headers["Author"]="liu"#添加响应头
    print("中间件m2响应被调用")
    return response

@app.middleware("http")
async def m1(request:Request, call_next):
    #请求代码块
    # if request.client.host in ["127.0.0.1"]:
    #     return Response(status_code=403, content="forbidden")

    # if request.url.path in ["/user"]:
    #     return Response(status_code=403, content="forbidden")

    start = time.time()

    print("中间件m1被调用")
    response = await call_next(request)
    #响应代码块
    end = time.time()
    response.headers["timer_process"]=str(end - start)
    print("中间件m1响应被调用")
    return response

@app.get("/user")
async def get_user():
    print("get_user函数")
    time.sleep(3)
    return{
        "user" : "current user"
    }

@app.get("/item/{item_id}")
async def get_item(item_id: int):
    print("get_item函数")
    return{
        "item_id" : {item_id}
    }

if __name__ == '__main__':
    uvicorn.run("main:app", port=8000, reload=True)

CORS

跨域资源共享(Cross-Origin Resource Sharing,CORS)是一种机制,它允许受限的资源(如字体、JavaScript等)在一个网页上被另一个域的网页访问。

  • 手写的
python 复制代码
@app.middleware("http")
async def CORSMiddleware(request: Request, call_next):
    response = await call_next(request)
    response.headers["Access-Control-Allow-Origin"] = "*"
    return response
  • 使用FastAPI内置的CORSMiddleware
python 复制代码
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有来源
    allow_credentials=True, # 允许携带凭证
    allow_methods=["*"],  # 允许所有方法
    allow_headers=["*"],  # 允许所有请求头
)
相关推荐
曲幽10 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
曲幽2 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
曲幽3 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
闲云一鹤4 天前
Python 入门(二)- 使用 FastAPI 快速生成后端 API 接口
python·fastapi
曲幽4 天前
FastAPI + Ollama 实战:搭一个能查天气的AI助手
python·ai·lora·torch·fastapi·web·model·ollama·weatherapi
百锦再5 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
SunnyRivers5 天前
LangChain中间件详解
中间件·langchain
金刚猿5 天前
06_虚拟机中间件部署_xxl-job 部署
中间件·xxl-job·xxl-job-admin
Li emily6 天前
解决了股票实时数据接口延迟问题
人工智能·fastapi