app.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. from contextlib import asynccontextmanager
  5. import argparse
  6. from fastapi import FastAPI, Request
  7. from fastapi.middleware.cors import CORSMiddleware
  8. from module.logger import logger
  9. from module.server.home_router import home_app
  10. from module.server.script_router import script_app
  11. from starlette import status
  12. from starlette.responses import JSONResponse
  13. @asynccontextmanager
  14. async def lifespan(app: FastAPI):
  15. await on_startup()
  16. yield
  17. await on_shutdown()
  18. app = FastAPI(
  19. title='OAS',
  20. description='OAS web service',
  21. version='0.0.0',
  22. lifespan=lifespan,
  23. )
  24. app.add_middleware(
  25. CORSMiddleware,
  26. allow_origins=["*"],
  27. allow_credentials=True,
  28. allow_methods=["*"],
  29. allow_headers=["*"]
  30. )
  31. app.include_router(home_app)
  32. app.include_router(script_app)
  33. async def on_startup():
  34. logger.info('OAS web service startup done')
  35. async def on_shutdown():
  36. logger.info('OAS web service shutdown done')
  37. @app.exception_handler(Exception)
  38. async def global_exception_handler(request: Request, exc: Exception):
  39. logger.error(f"Internal Server Error: ", exc_info=True)
  40. message = ', '.join(str(arg) for arg in exc.args) if exc.args else str(exc)
  41. return JSONResponse(
  42. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  43. content={
  44. 'message': message
  45. },
  46. )
  47. def fastapi_app():
  48. parser = argparse.ArgumentParser(description="OAS web service")
  49. parser.add_argument(
  50. "-k", "--key", type=str, help="Password of OAS. No password by default"
  51. )
  52. parser.add_argument(
  53. "--cdn",
  54. action="store_true",
  55. help="Use jsdelivr cdn for pywebio static files (css, js). Self host cdn by default.",
  56. )
  57. parser.add_argument(
  58. "--run",
  59. nargs="+",
  60. type=str,
  61. help="Run OAS by config names on startup",
  62. )
  63. args, _ = parser.parse_known_args()
  64. return app