FastAPI 静的ファイル
FastAPI は(画像、CSS、JavaScript ファイルなどの)静的ファイルサービスを簡単に提供でき、使用するのは Starlette のStaticFiles実装です。
依存関係のインストール
StaticFiles含まれています。aiofilesその中で、インストールが必要です:
pip install aiofiles
静的ファイルディレクトリのマウント
使用してapp.mount()静的ファイルディレクトリをアプリケーションにマウントします:
例
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
app = FastAPI()
# 静的ファイルディレクトリをマウント
# "/static" は URL パスのプレフィックスです
# directory="static" はローカルディレクトリ名です
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/")
async def root():
return {"message": "Hello World"}
from fastapi.staticfiles import StaticFiles
app = FastAPI()
# 静的ファイルディレクトリをマウント
# "/static" は URL パスのプレフィックスです
# directory="static" はローカルディレクトリ名です
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/")
async def root():
return {"message": "Hello World"}
コードの説明:
| パラメータ | 説明 |
|---|---|
"/static" | URL パスのプレフィックス。例: アクセス/static/logo.png |
directory="static" | ローカルディレクトリ名。静的ファイルを格納するフォルダ |
name="static" | 内部で使用する名前。URL を生成するために使用します(url_for) |
mount独立した「サブアプリケーション」を指定されたパスにマウントすることです。StaticFilesそれ自体が ASGI アプリケーションであり、静的ファイルのリクエストを処理します。マウント後、/staticで始まるリクエストはすべてStaticFiles処理され、FastAPI のルーティングシステムを経由しません。
ディレクトリ構造の例
project/
├── main.py
└── static/
├── css/
│ └── style.css
├── js/
│ └── app.js
└── images/
└── logo.png
アクセス方法:
| ファイルパス | URL |
|---|---|
static/css/style.css | http://127.0.0.1:8000/static/css/style.css |
static/js/app.js | http://127.0.0.1:8000/static/js/app.js |
static/images/logo.png | http://127.0.0.1:8000/static/images/logo.png |
HTMLテンプレートのレンダリング
FastAPI は Jinja2 テンプレートエンジンをサポートしており、HTMLページを動的にレンダリングできます:
例
from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
app = FastAPI()
# 静的ファイル
app.mount(
"/static",
StaticFiles(directory="static"),
name="static"
)
# Jinja2 テンプレート
templates = Jinja2Templates(
directory="templates"
)
@app.get("/hello/{name}")
async def hello(request: Request, name: str):
return templates.TemplateResponse(
request=request,
name="hello.html",
context={
"name": name
}
)
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
app = FastAPI()
# 静的ファイル
app.mount(
"/static",
StaticFiles(directory="static"),
name="static"
)
# Jinja2 テンプレート
templates = Jinja2Templates(
directory="templates"
)
@app.get("/hello/{name}")
async def hello(request: Request, name: str):
return templates.TemplateResponse(
request=request,
name="hello.html",
context={
"name": name
}
)
テンプレートファイルtemplates/hello.html:
例
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
<link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
<h1>Hello, {{ name }}!</h1>
<img src="/static/images/logo.png" alt="Logo">
</body>
</html>
<html>
<head>
<title>Hello</title>
<link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
<h1>Hello, {{ name }}!</h1>
<img src="/static/images/logo.png" alt="Logo">
</body>
</html>
テンプレートをレンダリングするときは、必ず
requestrequest オブジェクトを渡す必要があります。テンプレート内でリクエストコンテキスト(URL の生成など)が必要になる場合があるためです。
まとめ
- 使用して
StaticFiles静的ファイルサービスを提供します。 - 使用して
app.mount()静的ファイルディレクトリを指定されたパスにマウントします。 - マウント後の静的ファイルパスは FastAPI のルーティングシステムでは管理されません。
- Jinja2 テンプレートエンジンと組み合わせることで、HTMLページのレンダリングを実現できます。
- 静的ファイルは、CSS、JS、画像など、動的に変化しないリソースを格納するのに適しています。