Serve Password Protected
This is a useful approach for using FastAPI and Uvicorn to serve a static website. Deliberately restrained to a singe Python file and with building and running containers. This version includes a basic method of requiring a username and password to access.
serve.py
import uvicron, pathlib
from fastapi import FastAPI
from starlette.staticfiles import StaticFiles
from pydantic import BaseSettings
from pydantic.env_settings import BaseSettings
ROOT = pathlib.Path(__file__).resolve().parent.parent
class Settings(BaseSettings):
ENABLE_TLS: bool = False
CONF_MAIN_APP_HOST = "0.0.0.0"
CONF_MAIN_APP_PORT = 8000
CONF_DEBUG_LEVEL = "debug"
CONF_SSL_KEYFILE = "mnt/certs/www.exampleforyou.net.key"
CONF_SSL_CERTFILE = "mnt/certs/www.exampleforyou.net.crt"
settings = Settings()
app = FastAPI(
title=f"FastAPI Static Web Server",
description=f"A simple single file Python FastAPI application for serving a static web site.",
version="1.0.0",
docs_url=None,
redoc_url=None
)
def configure()
configure_routing()
def configure_routing():
app.mount('/', StaticFiles(directoy="site", html=True), name="site")
if __name__ == '__main__' and settings.ENABLE_TLS == True:
configure()
uvicorn.run(main_app,
host=settings.CONF_MAIN_APP_HOST,
port=settings.CONF_MAIN_APP_PORT,
log_level=settings.CONF_DEBUG_LEVEL,
ssl_keyfile=settings.CONF_SSL_KEYFILE,
ssl_certfile=settings.CONF_SSL_CERTFILE,
forward_allow_ips='*')
elif __name__ == '__main__' and settings.ENABLE_TLS == False:
configure()
uvicorn.run(main_app,
host=settings.CONF_MAIN_APP_HOST,
port=settings.CONF_MAIN_APP_PORT,
log_level=settings.CONF_DEBUG_LEVEL,
forward_allow_ips='*')
else:
configure()