エラー内容:
Error loading ASGI app. Could not import module "app".
実行時に指定するファイル名が異なっていることが原因です。
実行するコマンドを修正しましょう。
main.py
from fastapi import FastAPI, Response
from starlette.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.get("/")
def index():
return templates.TemplateResponse("index.html", context={"name": "World"})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)
uvicorn main:app --reload
index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Hello, {{ name }}</h1>
</body>
</html>
解決策:実行コマンドの修正
uvicorn ファイル名:app --reload
:appの前には実行するpythonファイルの名前を入れます。
main.pyの場合
uvicorn main:app --reload