server.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #!/usr/bin/env python3
  2. import json
  3. import operator
  4. import os
  5. import cleancss
  6. import tornado.gen
  7. import tornado.httpclient
  8. import tornado.ioloop
  9. import tornado.web
  10. from config import web as config
  11. class BaseHandler(tornado.web.RequestHandler):
  12. def render(self, *args, **kwargs):
  13. kwargs['host'] = config.host
  14. return super(BaseHandler, self).render(*args, **kwargs)
  15. def render_string(self, *args, **kwargs):
  16. s = super(BaseHandler, self).render_string(*args, **kwargs)
  17. return s.replace(b'\n', b'') # this is like Django's {% spaceless %}
  18. class MainHandler(BaseHandler):
  19. @tornado.web.asynchronous
  20. @tornado.gen.coroutine
  21. def get(self):
  22. http_client = tornado.httpclient.AsyncHTTPClient()
  23. kills_url = 'https://zkillboard.com/api/kills/corporationID/98182803/limit/1'
  24. losses_url = 'https://zkillboard.com/api/losses/corporationID/98182803/limit/1'
  25. kills_res, losses_res = yield [http_client.fetch(kills_url), http_client.fetch(losses_url)]
  26. kills = json.loads(kills_res.body.decode('utf-8'))
  27. losses = json.loads(losses_res.body.decode('utf-8'))
  28. kills = sorted(kills + losses, key=operator.itemgetter('killTime'), reverse=True)
  29. self.render('home.html', kills=kills)
  30. class CSSHandler(tornado.web.RequestHandler):
  31. def get(self, css_path):
  32. css_path = os.path.join(os.path.dirname(__file__), 'web', 'static', css_path) + '.ccss'
  33. with open(css_path, 'r') as f:
  34. self.set_header('Content-Type', 'text/css')
  35. self.write(cleancss.convert(f))
  36. if __name__ == '__main__':
  37. tornado.web.Application(
  38. handlers=[
  39. (r'/', MainHandler),
  40. (r"/(css/.+)\.css", CSSHandler),
  41. ],
  42. template_path=os.path.join(os.path.dirname(__file__), 'templates'),
  43. static_path=os.path.join(os.path.dirname(__file__), 'static'),
  44. cookie_secret=config.cookie_secret,
  45. debug=config.debug,
  46. ).listen(config.port)
  47. print('listening on :%d' % config.port)
  48. tornado.ioloop.IOLoop.instance().start()