app.py 3.0 KB

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