app.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  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. class NoCacheStaticFiles(StaticFiles):
  41. """
  42. 静态资源响应加 Cache-Control: no-cache:
  43. 浏览器仍可缓存,但每次都携带 ETag 回源校验,未变更返回 304。
  44. StaticFiles 默认不下发 Cache-Control,Edge 等按启发式缓存旧 JS,
  45. 前端更新后页面会继续执行旧脚本(表现为控件读不到数据/点了没反应)。
  46. """
  47. def file_response(self, *args, **kwargs):
  48. response = super().file_response(*args, **kwargs)
  49. response.headers["Cache-Control"] = "no-cache"
  50. return response
  51. if annotator_static_dir.exists():
  52. app.mount("/tool/annotator/static", NoCacheStaticFiles(directory=str(annotator_static_dir)), name="annotator_static")
  53. async def on_startup():
  54. """
  55. app.state 的生命周期在定义app的时候就有了
  56. :return:
  57. """
  58. logger.info('OAS web service startup done')
  59. if app.state.script_instances:
  60. await mm.restart_processes(app.state.script_instances)
  61. async def on_shutdown():
  62. logger.info('OAS web service shutdown done')
  63. @app.exception_handler(Exception)
  64. async def global_exception_handler(request: Request, exc: Exception):
  65. logger.error(f"Internal Server Error: ", exc_info=True)
  66. message = ', '.join(str(arg) for arg in exc.args) if exc.args else str(exc)
  67. return JSONResponse(
  68. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  69. content={
  70. 'message': message
  71. },
  72. )
  73. def fastapi_app():
  74. parser = argparse.ArgumentParser(description="OAS web service")
  75. parser.add_argument(
  76. "-k", "--key", type=str, help="Password of OAS. No password by default"
  77. )
  78. parser.add_argument(
  79. "--cdn",
  80. action="store_true",
  81. help="Use jsdelivr cdn for pywebio static files (css, js). Self host cdn by default.",
  82. )
  83. parser.add_argument(
  84. "--run",
  85. nargs="+",
  86. type=str,
  87. help="Run OAS by config names on startup",
  88. )
  89. args, _ = parser.parse_known_args()
  90. # ------------------------------------------------------------------------------------------------------------------
  91. runs = None
  92. if args.run:
  93. runs = args.run
  94. elif State.deploy_config.Run:
  95. # TODO: refactor poor_yaml_read() to support list
  96. tmp = State.deploy_config.Run.split(",")
  97. runs = [l.strip(" ['\"]") for l in tmp if len(l)]
  98. # ------------------------------------------------------------------------------------------------------------------
  99. app.state.script_instances = runs
  100. return app