app.py 2.7 KB

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