中间件与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=["*"],  # 允许所有请求头
)
相关推荐
ValidationExpression1 小时前
LangChain1.0学习
学习·ai·langchain·fastapi
曲幽1 小时前
FastAPI缓存提速实战:手把手教你用Redis为接口注入“记忆”
redis·python·cache·fastapi·web·asyncio
vivo互联网技术2 小时前
vivo 微服务架构实践之 Dubbo 性能优化
java·后端·微服务·中间件·dubbo
知行EDI2 小时前
宝兰德BES中间件的部署与启动实战:从环境搭建到知行之桥上线
中间件·edi·电子数据交换·知行之桥·信创·宝兰德bes
wang6021252183 小时前
流式输出注意点
python·状态模式·fastapi
利刃大大4 小时前
【RabbitMQ】消息确认机制 && 持久化 && 发布确认机制
分布式·中间件·消息队列·rabbitmq·mq
CCPC不拿奖不改名1 天前
基于FastAPI的API开发(爬虫的工作原理):从设计到部署详解+面试习题
爬虫·python·网络协议·tcp/ip·http·postman·fastapi
曲幽1 天前
FastAPI数据库实战:从SQLAlchemy原理到高效连接管理,告别性能瓶颈
python·sqlite·flask·fastapi·web·sqlalchemy·db