-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.py
74 lines (61 loc) · 2.13 KB
/
api.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
import os
import structlog
import aioredis
from aiohttp import web, helpers
logger = structlog.get_logger()
REDIS_HOST = os.getenv('REDIS_HOST', 'localhost')
REDIS_PORT = int(os.getenv('REDIS_PORT', '6379'))
REDIS_DB = int(os.getenv('REDIS_DB', '0'))
REDIS_PASS = os.getenv('REDIS_PASS', None)
APP_PASSWORD = os.getenv('APP_PASSWORD', None)
async def index(request):
return web.json_response({
'routes': [
'/v0/wrpi'
],
'description': 'randomising important numbers since 2021',
})
async def wrpi(request):
error_response = web.json_response({
'error': 'please authenticate to use this API',
'error_code': 'forbidden',
}, status=401, headers={
'WWW-Authenticate': 'Basic realm="wayhome wpri"',
})
try:
auth = helpers.BasicAuth.decode(
request.headers.get('authorization', ''))
except ValueError as e:
logger.debug('invalid auth header', exc_info=e)
return error_response
if auth.password != APP_PASSWORD:
logger.debug('invalid password', password=auth.password)
return error_response
value = await request.app['redis'].get('wrpi-latest')
timestamp = await request.app['redis'].get('wrpi-timestamp')
return web.json_response({
'latest_value': float(value.decode()),
'latest_calculation_at': timestamp.decode(),
})
async def redis_up(app):
logger.info(
'connecting to redis', host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB)
app['redis'] = await aioredis.create_redis_pool(
(REDIS_HOST, REDIS_PORT),
db=REDIS_DB,
password=REDIS_PASS,
)
logger.info('redis connected')
async def redis_down(app):
logger.info('closing redis connection pool')
app['redis'].close()
await app['redis'].wait_closed()
logger.info('redis pool closed')
if __name__ == '__main__':
structlog.configure(processors=[structlog.processors.JSONRenderer()])
app = web.Application()
app.router.add_get('/', index)
app.router.add_get('/v0/wrpi', wrpi)
app.on_startup.append(redis_up)
app.on_cleanup.append(redis_down)
web.run_app(app)