-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.py
107 lines (84 loc) · 2.62 KB
/
main.py
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from api.api import api_router
from asyncio import get_event_loop
from config import Config
from fastapi import APIRouter, FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from logging import basicConfig
from integrations.directus.directus import DirectusIntegration
from integrations.citrineos.citrineos import CitrineOSIntegration
from uvicorn import run
import stripe
from db.init_db import init_db
from integrations.integration import FileIntegration, OcppIntegration
basicConfig(format=Config.LOG_FORMAT, level=Config.LOG_LEVEL)
""" Create the Fast API web app and define cors. API router used to attach root path from Config. """
app = FastAPI(
title=Config.OPENAPI_TITLE,
)
router = APIRouter()
origins = [
"*",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_methods=["*"],
allow_headers=["*"],
)
""" On startup of the web app also start the event consumer and set stripe api key """
stripe.api_key = Config.STRIPE_API_KEY
file_integration: FileIntegration = DirectusIntegration(
Config.CITRINEOS_DIRECTUS_URL,
Config.CITRINEOS_DIRECTUS_LOGIN_EMAIL,
Config.CITRINEOS_DIRECTUS_LOGIN_PASSWORD,
)
ocpp_integration: OcppIntegration = CitrineOSIntegration(file_integration)
app.ocpp_integration = ocpp_integration
@app.on_event("startup")
async def startup_event():
loop = get_event_loop()
loop.create_task(coro=ocpp_integration.receive_events())
""" Add the API router to the web app """
app.include_router(
api_router,
prefix=Config.WEBSERVER_PATH,
)
""" Add a health check route """
@app.get("/health_check")
async def health_check():
return {"status": "healthy"}
""" Add the frontend web app """
templates = Jinja2Templates(directory="frontend/build")
frontend_routes = ["/", "/checkout/{evse_id}", "/charging/{evse_id}/{checkout_id}"]
async def serve_frontend(
request: Request,
):
return templates.TemplateResponse(
"index.html",
{
"request": request,
"CLIENT_API_URL": Config.CLIENT_URL + "/api",
},
)
for route in frontend_routes:
app.get(route, response_class=HTMLResponse)(serve_frontend)
app.mount(
"/",
StaticFiles(
directory="frontend/build",
),
name="frontend",
)
# Check if DB is reachable
# db = get_db()
# db.execute(text("select (1)"))
init_db()
if __name__ == "__main__":
try:
run(app, host=Config.WEBSERVER_HOST, port=Config.WEBSERVER_PORT)
except Exception as e:
# logger.error(e)
raise e