FastAPI 教程翻译 - 用户指南 33 - 静态文件
FastAPI Tutorial - User Guide - Static Files
You can serve static files automatically from a directory using StaticFiles
.
您可以使用 StaticFiles
从目录自动提供静态文件。
Install aiofiles
安装 aiofiles
First you need to install aiofiles
:
首先,您需要安装 aiofiles
:
pip install aiofiles
Use StaticFiles
使用 StaticFiles
-
Import
StaticFiles
.导入
StaticFiles
。 -
“Mount” a
StaticFiles()
instance in a specific path.在特定路径中『挂载』
StaticFiles()
实例。
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
Technical Details
技术细节
You could also use
from starlette.staticfiles import StaticFiles
.您也可以使用
from starlette.staticfiles import StaticFiles
。FastAPI provides the same
starlette.staticfiles
asfastapi.staticfiles
just as a convenience for you, the developer. But it actually comes directly from Starlette.FastAPI 提供与
fastapi.staticfiles
相同的starlette.staticfiles
,以方便开发人员。但实际上它直接来自 Starlette。
What is “Mounting”
什么是『挂载』
“Mounting” means adding a complete “independent” application in a specific path, that then takes care of handling all the sub-paths.
『挂载』是指在特定路径中添加完整的『独立』应用程序,然后负责处理所有子路径。
This is different from using an APIRouter
as a mounted application is completely independent. The OpenAPI and docs from your main application won’t include anything from the mounted application, etc.
这与使用 APIRouter
不同,因为已安装的应用程序是完全独立的。主应用程序中的 OpenAPI 和文档不会包含已安装应用程序中的任何内容,等等。
You can read more about this in the Advanced User Guide.
您可以在高级用户指南中阅读有关此内容的更多信息。
Details
细节
The first "/static"
refers to the sub-path this “sub-application” will be “mounted” on. So, any path that starts with "/static"
will be handled by it.
第一个 "/static"
是指将『挂载』该『子应用程序』的子路径。因此,任何以 "/static"
开头的路径都将被它处理。
The directory="static"
refers to the name of the directory that contains your static files.
directory="static"
是指包含您的静态文件的目录的名称。
The name="static"
gives it a name that can be used internally by FastAPI.
name="static"
为它提供了一个名称,供 FastAPI 在内部使用。
All these parameters can be different than “static
”, adjust them with the needs and specific details of your own application.
所有这些参数都可以不同于 "static"
参数,根据您自己的应用程序的需求和特定细节进行调整。
More info
更多信息
For more details and options check Starlette’s docs about Static Files.
有关更多详细信息和选项,请查看 有关静态文件的 Starlette 文档。