webserver.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import json
  2. import logging
  3. import os
  4. from aiohttp import web
  5. from aiohttp.web_urldispatcher import Response
  6. STATIC_INDEX = '''
  7. <!DOCTYPE html>
  8. <html>
  9. <head>
  10. <meta charset="utf-8">
  11. <meta name="viewport" content="width=device-width, initial-scale=1">
  12. </head>
  13. <body>
  14. <div id="app">Nothing to see here...</div>
  15. </html>
  16. '''
  17. class WebServer(object):
  18. def __init__(self, _loop, transparency_watcher):
  19. self.stats_url = os.getenv("STATS_URL", 'stats')
  20. self.logger = logging.getLogger('certstream.webserver')
  21. self.loop = _loop
  22. self.watcher = transparency_watcher
  23. self.app = web.Application(loop=self.loop)
  24. self._add_routes()
  25. def run_server(self):
  26. web.run_app(
  27. self.app,
  28. port=int(os.environ.get('PORT', 8080)),
  29. ssl_context=None
  30. )
  31. def _add_routes(self):
  32. self.app.router.add_get("/{}".format(self.stats_url), self.stats_handler)
  33. self.app.router.add_get('/', self.root_handler)
  34. async def root_handler(self, request):
  35. return Response(body=STATIC_INDEX, content_type="text/html")
  36. async def stats_handler(self, _):
  37. return web.Response(
  38. body=json.dumps({
  39. "last_seen": self.watcher.lastseen,
  40. }, indent=4
  41. ),
  42. content_type="application/json",
  43. )