main.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. from fastapi import FastAPI, Request
  2. from fastapi.staticfiles import StaticFiles
  3. from fastapi import HTTPException
  4. from fastapi.middleware.wsgi import WSGIMiddleware
  5. from fastapi.middleware.cors import CORSMiddleware
  6. from starlette.exceptions import HTTPException as StarletteHTTPException
  7. from apps.ollama.main import app as ollama_app
  8. from apps.openai.main import app as openai_app
  9. from apps.web.main import app as webui_app
  10. import time
  11. class SPAStaticFiles(StaticFiles):
  12. async def get_response(self, path: str, scope):
  13. try:
  14. return await super().get_response(path, scope)
  15. except (HTTPException, StarletteHTTPException) as ex:
  16. if ex.status_code == 404:
  17. return await super().get_response("index.html", scope)
  18. else:
  19. raise ex
  20. app = FastAPI()
  21. origins = ["*"]
  22. app.add_middleware(
  23. CORSMiddleware,
  24. allow_origins=origins,
  25. allow_credentials=True,
  26. allow_methods=["*"],
  27. allow_headers=["*"],
  28. )
  29. @app.middleware("http")
  30. async def check_url(request: Request, call_next):
  31. start_time = int(time.time())
  32. response = await call_next(request)
  33. process_time = int(time.time()) - start_time
  34. response.headers["X-Process-Time"] = str(process_time)
  35. return response
  36. app.mount("/api/v1", webui_app)
  37. app.mount("/ollama/api", ollama_app)
  38. app.mount("/openai/api", openai_app)
  39. app.mount("/",
  40. SPAStaticFiles(directory="../build", html=True),
  41. name="spa-static-files")