在 FastAPI 中从根目录提供静态文件

sha*_*red 17 svelte fastapi

我正在尝试让 FastAPI 与 Svelte 一起工作。我已经使用 Svelte 构建了静态文件,现在我尝试通过 FastAPI 提供它们。问题是构建的 Svelte 文件global.css从根目录引用,这意味着我无法将它们安装在子文件夹中。

相反,我必须将它们安装在 root 上:

app.mount("/", StaticFiles(directory="web/public", html=True), name="web")
Run Code Online (Sandbox Code Playgroud)

然而,这使得路由(函数装饰器)中定义的任何内容都无法访问。

是否可以同时定义静态文件函数?任何一个,

a) 路由优先,如果没有路由,它会尝试从静态目录中读取

b) 静态目录优先,我指定了一个排除路径,该路径改为路由

ldr*_*drg 17

创建外部(根)FastAPI 应用程序并在其中安装 StaticFiles 应用程序和现有的 FastAPI 应用程序。

# Your main app must be first!
app = FastAPI(title="my app root")

api_app = FastAPI(title="my existing api")
api_app.include_router(my_existing_router)
app.mount('/api', api_app)

app.mount('/', StaticFiles(directory="static", html=True), name="static")
Run Code Online (Sandbox Code Playgroud)

应用程序对象的安装顺序似乎很重要。对于 OpenAPI 文档,您将有一个/docs用于根应用程序的文档,一个/api/docs用于您的 API 应用程序的文档。


pie*_*etz 14

我认为有一个比此处发布的解决方案更简单的解决方案:只需在定义其他端点后安装静态文件夹即可。

app = FastAPI()

@app.get("/api/hello")
async def hello():
    return "hello from fastapi"

app.mount("/", StaticFiles(directory="build", html=True), name="frontend")
Run Code Online (Sandbox Code Playgroud)

您现在可以访问作为根静态站点的网站,同时还可以访问您可能想要用于后端功能的端点。