This repository has been archived by the owner on Mar 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
63 lines (48 loc) · 1.64 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
from asyncio import CancelledError
import aiohttp.hdrs
import prometheus_client
from aiohttp import web
from prometheus_client.exposition import choose_encoder
import config
from mb_api import MbCustomer, MbHybridVehicle
async def app_factory():
customer = MbCustomer(
client_id=config.client_id, client_secret=config.client_secret
)
my_hybrid = MbHybridVehicle(customer, config.vin)
routes = web.RouteTableDef()
@routes.get("/metrics")
async def metrics(request: web.Request):
encoder, content_type = choose_encoder(request.headers["accept"])
output = encoder(prometheus_client.REGISTRY)
return web.Response(
body=output,
headers={aiohttp.hdrs.CONTENT_TYPE: content_type},
)
@routes.get("/oauth.auth")
async def auth(_: web.Request):
if not customer.authorized:
raise web.HTTPFound(customer.authorization_url()[0])
return web.Response(text="Authorized")
@routes.get("/oauth.redirect")
async def redirect(request: web.Request):
customer.fetch_token(**request.query)
customer.persist()
if not my_hybrid.running():
my_hybrid.start()
raise web.HTTPFound("/metrics")
async def fetch_hybrid(_):
my_hybrid.start()
yield
my_hybrid.stop()
try:
if my_hybrid.continuous_refresh_task:
await my_hybrid.continuous_refresh_task
except CancelledError:
pass
customer.persist()
app = web.Application()
app.add_routes(routes)
app.cleanup_ctx.append(fetch_hybrid)
return app
web.run_app(app_factory())