server.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #!/usr/bin/env python3
  2. import json
  3. import operator
  4. import os
  5. import cleancss
  6. import tornado.httpclient
  7. import tornado.ioloop
  8. import tornado.web
  9. from config import web as config
  10. import db
  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. def get(self):
  20. self.render('home.html')
  21. class SearchHandler(BaseHandler):
  22. def get(self):
  23. q = self.get_argument('q')
  24. with db.cursor() as c:
  25. corps = db.query(c, '''
  26. SELECT DISTINCT corporation_id, corporation_name FROM characters
  27. WHERE corporation_name LIKE ?
  28. ''', '%{}%'.format(q))
  29. self.render('search.html', corps=corps)
  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'/search', SearchHandler),
  41. (r"/(css/.+)\.css", CSSHandler),
  42. ],
  43. template_path=os.path.join(os.path.dirname(__file__), 'web/templates'),
  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()