FastAPI 教程翻译 - 用户指南 33 - 静态文件

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 as fastapi.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 文档

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值