hook.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #!/usr/bin/env python
  2. """
  3. @Contact : liuyuqi.gov@msn.cn
  4. @Time : 2024/03/24 13:48:03
  5. @License : Copyright © 2017-2022 liuyuqi. All Rights Reserved.
  6. @Desc :
  7. """
  8. import logging
  9. from app.api import api_router
  10. from app.config import settings
  11. from starlette.middleware.cors import CORSMiddleware
  12. from fastapi import FastAPI
  13. def init_banner():
  14. """
  15. Print banner
  16. """
  17. banner = """
  18. FastAPI Example
  19. concat me: liuyuqi.gov@msn.cn
  20. """
  21. print(banner)
  22. def init_logging(logger_name: str) -> logging:
  23. """
  24. Initialize logger
  25. """
  26. logger = logging.getLogger(logger_name)
  27. logger.setLevel(logging.DEBUG)
  28. if logger.hasHandlers():
  29. logger.handlers.clear()
  30. for handler in self.available_handlers:
  31. logger.addHandler(handler)
  32. logger.propagate = False
  33. return logger
  34. def init_hook(app: FastAPI):
  35. @app.on_event("startup")
  36. async def startup_event():
  37. print("Application started")
  38. # await initiate_database()
  39. @app.on_event("shutdown")
  40. async def shutdown_event():
  41. print("Application shutdown")
  42. # await close_database_connection_pool()
  43. def init_middlewares(app: FastAPI):
  44. """Add CORS middleware to allow all origins"""
  45. if settings.BACKEND_CORS_ORIGINS:
  46. app.add_middleware(
  47. CORSMiddleware,
  48. allow_origins=[
  49. str(origin).strip("/") for origin in settings.BACKEND_CORS_ORIGINS
  50. ],
  51. allow_credentials=True,
  52. # allow_methods=["*"],
  53. allow_methods=("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"),
  54. allow_headers=["*"],
  55. )
  56. # @fastapp.middleware('http')
  57. # async def add_process_time_header(request: Request, call_next): # call_next将接收request请求做为参数
  58. # start_time = time.time()
  59. # response = await call_next(request)
  60. # process_time = time.time() - start_time
  61. # response.headers['X-Process-Time'] = str(process_time) # 添加自定义的以“X-”开头的请求头
  62. # return response
  63. # fastapp.mount(path='/static', app=StaticFiles(directory='./coronavirus/static'), name='static')
  64. def register_db(app: FastAPI):
  65. """Register database connection"""
  66. pass
  67. # with Session(engine) as session:
  68. # initate_postgres(session)
  69. def register_exception_handlers(app: FastAPI):
  70. """Register exception handlers"""
  71. pass
  72. def register_routes(app: FastAPI):
  73. """Register all routes"""
  74. app.include_router(api_router)