From 76270db704a992f5585bc02907824c4affcddab6 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Fri, 24 May 2024 09:00:32 -1000 Subject: [PATCH] FastAPI startup events This was added a few months ago but seems to have since been clobbered. Testing again. --- src/panoptes/pocs/utils/service/power.py | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/src/panoptes/pocs/utils/service/power.py b/src/panoptes/pocs/utils/service/power.py index 81c386665..aad5be027 100644 --- a/src/panoptes/pocs/utils/service/power.py +++ b/src/panoptes/pocs/utils/service/power.py @@ -1,3 +1,4 @@ +from contextlib import asynccontextmanager from enum import auto from typing import Union @@ -20,19 +21,24 @@ class RelayCommand(BaseModel): command: RelayAction -app = FastAPI() power_board: PowerBoard -conf = get_config('environment.power', {}) +conf: dict -@app.on_event('startup') -async def startup(): +@asynccontextmanager +def lifespan(app: FastAPI): + global conf global power_board - power_board = PowerBoard(**get_config('environment.power', {})) - print(f'Power board setup: {power_board}') + conf = get_config('environment.power', {}) + power_board = PowerBoard(**conf) + power_board.logger.info(f'Power board setup: {power_board}') + yield + power_board.logger.info('Shutting down power board') + + +app = FastAPI() -@app.on_event('startup') @repeat_every(seconds=conf.get('record_interval', 60), wait_first=True) def record_readings(): """Record the current readings in the db."""