【发布时间】:2020-06-18 20:37:17
【问题描述】:
我需要提供一个包含数据的目录,例如 Apache 如何提供索引,我想通过我的 FastAPI 应用程序提供它。
FastAPI 或 Starlette 可以做到吗?
如果不是,Simplehttpserver alternatives 建议将 Twistd 作为 python 包。是否可以将 FastAPI 重定向到目录挂载处的扭曲服务器?
【问题讨论】:
我需要提供一个包含数据的目录,例如 Apache 如何提供索引,我想通过我的 FastAPI 应用程序提供它。
FastAPI 或 Starlette 可以做到吗?
如果不是,Simplehttpserver alternatives 建议将 Twistd 作为 python 包。是否可以将 FastAPI 重定向到目录挂载处的扭曲服务器?
【问题讨论】:
您正在寻找StaticFiles 实用程序:
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
app = FastAPI()
app.mount("/", StaticFiles(directory="static"), name="static")
参数用法记录在FastAPI documentation:
第一个"/" 指的是这个“子应用程序”将被“挂载”到的路径。在这种情况下,所有路径都将由它处理。
directory="static" 是指包含本地文件系统上的静态文件的目录的名称。
name="static" 为其提供了一个可供 FastAPI 内部使用的名称。
所有这些参数都可以不同于“静态”,根据您自己应用程序的需要和具体细节进行调整。
注意:你需要安装aiofiles:
pip install aiofiles
【讨论】: