FastAPI学习(四)——中间件

发布于:2025-09-13 ⋅ 阅读:(20) ⋅ 点赞:(0)

FastAPI中间件

中间件

中间件就是传话的人,消息进来的时候带进来,消息发出的时候带出去,在带进来和带出去的过程中可以自定义一些处理操作。

写法

在FastAPI中,可以通过装饰器@app.middleware()或者调用函数app.add_middleware()的方式注册中间件,先注册的中间件靠近信息处理中心,后注册的包在外面。

import time

from fastapi import FastAPI, Request

app = FastAPI()

# 所有http请求都会通过这个中间件,目前暂且只有这一种
# 这里指的是基于ASGI的HTTP协议事件,HTTPS = HTTP + TLS加密层,在到达FastAPI之前已经解密了
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
	# 传送request途中
	start_time = time.perf_counter()
	
	# 把request送给路径操作函数
	response = await call_next(request)
	
	# 送出response途中
	process_time = time.perf_counter() - start_time
	# 在header中加入自定义的属性,注意添加自定义属性需要以"X-"前缀开头。
	response.headers["X-Process-Time"] = str(process_time)
	return response

CORS 跨域资源共享

Cross Origin Resource Sharing

这里的Origin(源/域)指的是:协议、域名、端口的总和,必须三个都一样才叫一个源。

在实际开发中,CORS主要解决前后端分离时的跨域问题、团队协作开发的跨域问题。

FastAPI提供了内置的CORS支持,让跨域资源共享的配置变得简单而灵活。

  1. 安装和导入
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()
  1. 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://localhost:3000"],  # 允许的源
    allow_credentials=True,                    # 允许携带凭证
    allow_methods=["*"],                       # 允许的HTTP方法
    allow_headers=["*"],                       # 允许的请求头
)

详细参数说明:

allow_origins
指定允许访问的源列表:

# 允许特定域名
allow_origins=[
    "https://localhost:3000",
    "https://myapp.com",
    "https://www.myapp.com"
]

# 允许所有域名(开发环境)
allow_origins=["*"]

# 使用正则表达式
allow_origin_regex=r"https://.*\.myapp\.com"

allow_methods
指定允许的HTTP方法:

# 允许所有方法
allow_methods=["*"]

# 允许特定方法
allow_methods=["GET", "POST", "PUT", "DELETE"]

# 只允许读操作
allow_methods=["GET", "HEAD", "OPTIONS"]

allow_headers
指定允许的请求头:

# 允许所有请求头
allow_headers=["*"]

# 允许特定请求头
allow_headers=["Content-Type", "Authorization", "X-Requested-With"]

allow_credentials
是否允许携带凭证(cookies、authorization headers等):

# 允许携带凭证
allow_credentials=True

# 不允许携带凭证
allow_credentials=False