-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
87 lines (68 loc) · 2.73 KB
/
Copy pathmain.py
File metadata and controls
87 lines (68 loc) · 2.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
from contextlib import asynccontextmanager
from fastapi import APIRouter, FastAPI, HTTPException
from loguru import logger
from pydantic import BaseModel
from pydantic_yaml import YamlModel
from typing import Optional
class Payload(BaseModel):
"""mocks the payloads to your endpoints to control the typing of the incoming json objects"""
string: str
integer: int
optional_param: Optional[str] = None
class AppConfig(YamlModel):
"""Allows easy config of the app via a yaml file: see start_up()"""
mockMode: bool
debugMode: bool
class MyApp:
def __init__(self, config: AppConfig):
self.config = config
self.router = APIRouter()
self.router.add_api_route("/endpoint", self.endpoint, methods=["POST"])
self.router.add_api_route("/liveness", self.liveness, methods=["GET"])
self.router.add_api_route("/readiness", self.liveness, methods=["GET"])
def endpoint(self, payload: Payload):
print(payload)
if self.config.mockMode:
return {"message": "mock_mode enabled"}
else:
response = self.construct_payload(payload.string, payload.integer, payload.optional_param)
return {"message": response}
@staticmethod
def construct_payload(string: str, integer: int, optional_param) -> str:
"""dummy func to ensure get function cleanliness"""
if optional_param is None:
return f"endpoint called with payload: {string} {integer}"
else:
return f"endpoint called with payload: {string} {integer}, {optional_param}"
def build_app(self):
return FastAPI(lifespan=self.lifespan)
@asynccontextmanager
async def lifespan(self, __app: FastAPI):
"""Handle the start_up/shut_down of app (pre/post *yield* keyword)"""
try:
self.start_up()
__app.include_router(self.router)
logger.info("app started with config: " + str(self.config))
except Exception as e:
logger.critical("failed to start up app: " + str(e))
exit()
yield
self.shut_down()
def start_up(self):
"""called on app start up"""
logger.info(f"app starting with config: {self.config}")
# self.app.include_router(self.router)
def shut_down(self):
"""called on app shut down"""
logger.info("app gracefully shutting down")
def liveness(self):
"""kubernetes liveliness probe"""
return {"status": "ok"}
def readiness(self):
"""kubernetes readiness probe"""
return {"status": "ok"}
config = AppConfig.parse_file( "config/config.yaml")
# uvicorn looks for a fastApi object called app in main.py
# uvicorn main:app
my_app = MyApp(config)
app = my_app.build_app()