【问题标题】:How to add custom headers to static files in fastapi如何将自定义标头添加到 fastapi 中的静态文件
【发布时间】:2023-02-01 00:22:01
【问题描述】:
我们使用以下方法从目录挂载静态文件
app.mount("/static", StaticFiles(directory="static"), name="static")
在向客户端发送响应之前,我们使用通用方法为安全相关步骤发送了 api 的自定义标头。
有没有办法将安全标头发送到相同类型标头的 css/js/html 静态文件。 ?
只想知道将自定义标头发送到静态文件的方式或方法。
【问题讨论】:
标签:
python
python-3.x
static
fastapi
【解决方案1】:
像这样
from fastapi import FastAPI
from fastapi.responses import FileResponse
app = FastAPI()
@app.get("/static/{file_path:path}")
async def function(file_path: str):
response = FileResponse(f"static/{file_path}")
response.headers["X-Custom-Header"] = "Your custom header value"
return response
你可以看到更多here