11
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

FastApiで静的ファイルをマウントする

Posted at

概要

  • FastApiで静的ファイルを表示するときの備忘録
  • index.htmlを自動で読み込みたければ設定が必要

構成

.
├── main.py
└── static
    ├── favicon.ico
    ├── index.html
    └── static
        ├── css
        └── js

静的ファイルのマウント

StaticFilesをimportしてdirectory指定することでマウントできます。
ただし、このままだと/staticにアクセスしてもindex.htmlは表示されません。

main.py
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()

app.mount("/static", StaticFiles(directory="static"), name="static")

対応方法

HTMLモードを有効にします。

FastApiのサイトには書いてないですが、starletteのサイトに書いてあります。

main.py
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()

app.mount("/static", StaticFiles(directory="static", html=True), name="static")

参考

11
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?