app.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. from pathlib import Path
  5. from contextlib import asynccontextmanager
  6. import argparse
  7. from starlette import status
  8. from starlette.responses import JSONResponse
  9. from fastapi import FastAPI, Request
  10. from fastapi.middleware.cors import CORSMiddleware
  11. from module.logger import logger
  12. from module.server.home_router import home_app
  13. from module.server.script_router import script_app
  14. from module.server.tool_router import tool_app
  15. from module.server.setting import State
  16. from module.server.main_manager import mm
  17. from starlette.staticfiles import StaticFiles
  18. @asynccontextmanager
  19. async def lifespan(app: FastAPI):
  20. await on_startup()
  21. yield
  22. await on_shutdown()
  23. app = FastAPI(
  24. title='OAS',
  25. description='OAS web service',
  26. version='0.0.0',
  27. lifespan=lifespan,
  28. )
  29. app.add_middleware(
  30. CORSMiddleware,
  31. allow_origins=["*"],
  32. allow_credentials=True,
  33. allow_methods=["*"],
  34. allow_headers=["*"]
  35. )
  36. app.include_router(home_app)
  37. app.include_router(script_app)
  38. app.include_router(tool_app)
  39. annotator_static_dir = Path(__file__).resolve().parent / "web" / "annotator" / "static"
  40. if annotator_static_dir.exists():
  41. app.mount("/tool/annotator/static", StaticFiles(directory=str(annotator_static_dir)), name="annotator_static")
  42. async def on_startup():
  43. """
  44. app.state 的生命周期在定义app的时候就有了
  45. :return:
  46. """
  47. logger.info('OAS web service startup done')
  48. if app.state.script_instances:
  49. await mm.restart_processes(app.state.script_instances)
  50. async def on_shutdown():
  51. logger.info('OAS web service shutdown done')
  52. @app.exception_handler(Exception)
  53. async def global_exception_handler(request: Request, exc: Exception):
  54. logger.error(f"Internal Server Error: ", exc_info=True)
  55. message = ', '.join(str(arg) for arg in exc.args) if exc.args else str(exc)
  56. return JSONResponse(
  57. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  58. content={
  59. 'message': message
  60. },
  61. )
  62. def fastapi_app():
  63. parser = argparse.ArgumentParser(description="OAS web service")
  64. parser.add_argument(
  65. "-k", "--key", type=str, help="Password of OAS. No password by default"
  66. )
  67. parser.add_argument(
  68. "--cdn",
  69. action="store_true",
  70. help="Use jsdelivr cdn for pywebio static files (css, js). Self host cdn by default.",
  71. )
  72. parser.add_argument(
  73. "--run",
  74. nargs="+",
  75. type=str,
  76. help="Run OAS by config names on startup",
  77. )
  78. args, _ = parser.parse_known_args()
  79. # ------------------------------------------------------------------------------------------------------------------
  80. runs = None
  81. if args.run:
  82. runs = args.run
  83. elif State.deploy_config.Run:
  84. # TODO: refactor poor_yaml_read() to support list
  85. tmp = State.deploy_config.Run.split(",")
  86. runs = [l.strip(" ['\"]") for l in tmp if len(l)]
  87. # ------------------------------------------------------------------------------------------------------------------
  88. app.state.script_instances = runs
  89. return app