main.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import json
  2. from tornado import httpserver
  3. from tornado.ioloop import IOLoop
  4. from tornado.options import define
  5. from tornado.web import Application, RequestHandler
  6. from server import db
  7. define("port", default=3002, help="Default port for the WebServer")
  8. class XMasRequestHandler(RequestHandler):
  9. def set_default_headers(self):
  10. origin = self.request.headers.get('Origin')
  11. if origin in ['http://localhost:3001', 'http://localhost', 'http://127.0.0.1', 'http://christmas.logicp.ca']:
  12. self.set_header("access-control-allow-origin", origin)
  13. self.set_header("Access-Control-Allow-Headers", "x-requested-with")
  14. self.set_header('Access-Control-Allow-Methods', 'GET, PUT, DELETE, OPTIONS')
  15. # HEADERS!
  16. self.set_header("Access-Control-Allow-Headers", "access-control-allow-origin,authorization,content-type")
  17. class AttendeeHandler(XMasRequestHandler):
  18. def data_received(self, chunk):
  19. pass
  20. def options(self, *args, **kwargs):
  21. pass
  22. async def post(self, *args, **kwargs):
  23. print(self.request.body)
  24. data = json.loads(self.request.body.decode('utf-8'))
  25. result = await db.add_attendee(data['name'], data['guest'], data['cat'])
  26. self.write(json.dumps({'response': str(result), 'error': str(not result)}))
  27. class ListHandler(XMasRequestHandler):
  28. async def get(self, *args, **kwags):
  29. attendees = await db.fetch_attendees()
  30. self.write(json.dumps({'attendees': [{'name': x.name, 'guest': x.guest, 'cat': x.cat} for x in attendees]}))
  31. class ChristmasApplication(Application):
  32. def __init__(self):
  33. self.session = None
  34. handlers = [
  35. # Home
  36. (r"/list", ListHandler),
  37. # User GUI
  38. # - Profile
  39. (r"/attendee", AttendeeHandler),
  40. ]
  41. settings = {
  42. "debug": True,
  43. "cookie_secret": "ashda89sduaosihdsauDIOh",
  44. }
  45. Application.__init__(self, handlers, **settings)
  46. if __name__ == "__main__":
  47. application = ChristmasApplication()
  48. http_server = httpserver.HTTPServer(application)
  49. http_server.listen(3002)
  50. db.Base.metadata.create_all(bind=db.engine)
  51. loop_instance = IOLoop.instance()
  52. loop_instance.start()