Home > Net >  How can I load an index.html file using Fast API on the localhost?
How can I load an index.html file using Fast API on the localhost?

Time:09-21

I have tried : app.mount("", StaticFiles(directory="index.html", html = True), name="index.html")

as well as :

templates = Jinja2Templates(directory="/")

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

@app.get("/")
def serve_home(request: Request):
    return templates.TemplateResponse("index.html", context= {"request": request})

In both cases I could not import static files using : from fastapi.staticfiles import StaticFiles

It seems from fastapi import FastAPI also could not be resolved but that did not stop the program from working before I tried loading the html file,

CodePudding user response:

You just need code:

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

app = FastAPI()
# first 'static' specify route path, second 'static' specify html files directory.
app.mount('/static', StaticFiles(directory='static',html=True))
if __name__ == '__main__':
    uvicorn.run(app, host='0.0.0.0')

After running main.py, access by http://127.0.0.1:8000/static/index.html
the project tree is:

$ tree app
app
├── main.py
└── static
    └── index.html

Reference https://fastapi.tiangolo.com/tutorial/static-files/.

Hope this is useful.

  • Related