1.基础用法
1 2 3 4 5 6 7 8 9 10 11
| from fastapi import FastAPI from fastapi.staticfiles import StaticFiles
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/") async def main(): return {"message": "访问静态文件请前往 /static/example.txt"}
|
- 使用
StaticFiles中间件托管静态文件目录
directory参数指定本地静态文件目录路径
name参数为挂载点命名(用于内部标识)
请求处理流程:
graph TD
A[请求 /static/style.css] --> B{文件存在?}
B -->|是| C[返回文件内容]
B -->|否| D[返回404错误]
C --> E[自动识别MIME类型]
2.进阶配置
2.1 HTML文件托管
1 2 3 4 5
| app.mount("/site", StaticFiles(directory="html", html=True), name="website")
app.mount("/", StaticFiles(directory="public", html=True), name="root")
|
html=True启用HTML模式,自动处理index.html
- 优先级:精确路由 > 静态文件 > 路径参数路由
2.2 缓存控制
1 2 3 4 5 6 7
| from fastapi.staticfiles import StaticFiles
app.mount("/assets", StaticFiles( directory="assets", max_age=3600, check_dir_exists=True ), name="assets")
|
max_age设置Cache-Control响应头(秒)
check_dir_exists启动时验证目录是否存在
3.生产环境建议
- 性能优化:
- 使用Nginx处理静态文件减轻应用压力
- 对静态资源启用CDN加速
- 安全配置:
- 限制静态目录访问权限(禁用执行权限)
- 防止路径穿越攻击(框架已内置防护)
- 版本管理:
- 使用文件哈希值命名实现长期缓存
- 示例:
style.abcd1234.css
- 混合路由:
- API路由与静态路由分离部署
- 通过前缀区分不同功能模块
测试命令示例:
1 2 3 4 5
| mkdir static && echo "Hello FastAPI" > static/hello.txt
curl http://localhost:8000/static/hello.txt
|