🐛 fix(main.py): add a custom 404 handler to return the index.html file when a 404 error occurs

The create_app function now accepts a static_path parameter that defaults to "static". The setup_static_files function is created to mount the static files directory to the app. A custom 404 handler is added to the app to return the index.html file when a 404 error occurs. This allows the app to serve static files such as HTML, CSS, and JavaScript files.
🚀 feat(__main__.py, main.py): add support for serving static files
 feat(__main__.py): create a setup_static_files function to mount the static files directory to the app
This commit is contained in:
Gabriel Luiz Freitas Almeida 2023-06-15 20:48:01 -03:00
commit 12db6f52fb
2 changed files with 26 additions and 7 deletions

View file

@ -1,5 +1,6 @@
import sys
import time
from fastapi import FastAPI
import httpx
from multiprocess import Process, cpu_count # type: ignore
import platform
@ -145,18 +146,16 @@ def serve(
update_settings(
config, dev=dev, database_url=database_url, remove_api_keys=remove_api_keys
)
app = create_app()
# get the directory of the current file
if not path:
frontend_path = Path(__file__).parent
static_files_dir = frontend_path / "frontend"
else:
static_files_dir = Path(path)
app.mount(
"/",
StaticFiles(directory=static_files_dir, html=True),
name="static",
)
app = create_app(static_files_dir)
setup_static_files(app, static_files_dir)
options = {
"bind": f"{host}:{port}",
"workers": get_number_of_workers(workers),
@ -180,6 +179,21 @@ def serve(
webbrowser.open(f"http://{host}:{port}")
def setup_static_files(app: FastAPI, static_files_dir: str):
"""
Setup the static files directory.
Args:
app (FastAPI): FastAPI app.
path (str): Path to the static files directory.
"""
app.mount(
"/",
StaticFiles(directory=static_files_dir, html=True),
name="static",
)
def print_banner(host, port):
# console = Console()

View file

@ -1,11 +1,12 @@
from fastapi import FastAPI
from fastapi.responses import FileResponse
from fastapi.middleware.cors import CORSMiddleware
from langflow.api import router
from langflow.database.base import create_db_and_tables
def create_app():
def create_app(static_path: str = "static"):
"""Create the FastAPI app and include the router."""
app = FastAPI()
@ -17,6 +18,10 @@ def create_app():
def get_health():
return {"status": "OK"}
@app.exception_handler(404)
async def custom_404_handler(request, __):
return FileResponse(f"{static_path}/index.html")
app.add_middleware(
CORSMiddleware,
allow_origins=origins,