server.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import tornado.ioloop
  2. import tornado.web
  3. from tornado import gen
  4. import motor
  5. import random
  6. from tornado import escape
  7. import tornado.options
  8. from tornado.options import options
  9. tornado.options.define('port', default=8888, type=int, help=(
  10. "Server port"))
  11. db = motor.MotorClient("127.0.0.1").open_sync().hello_world
  12. class JsonSerializeTestHandler(tornado.web.RequestHandler):
  13. @tornado.web.asynchronous
  14. @gen.coroutine
  15. def get(self):
  16. obj = dict(message="Hello, World!")
  17. self.write(obj)
  18. class QueryTestHandler(tornado.web.RequestHandler):
  19. @tornado.web.asynchronous
  20. @gen.coroutine
  21. def get(self):
  22. queries = int(self.get_argument("queries", 0))
  23. if queries == 0:
  24. random_id = random.randint(1, 10000)
  25. world = yield gen.Task(db.world.find_one,{"id": random_id}, fields={"_id": 0, "id": 1, "randomNumber": 1})
  26. # Get first postion on arguments, and so first postion in mongo return
  27. world = world[0][0]
  28. else:
  29. worlds = []
  30. for i in xrange(int(queries)):
  31. random_id = random.randint(1, 10000)
  32. world = yield gen.Task(db.world.find_one,{"id": random_id}, fields={"_id": 0, "id": 1, "randomNumber": 1})
  33. # Get first postion on arguments, and so first postion in mongo return
  34. worlds.append(world[0][0])
  35. worlds = escape.json_encode(worlds)
  36. self.set_header("Content-Type", "application/json; charset=UTF-8")
  37. self.write(worlds if queries > 0 else world)
  38. application = tornado.web.Application([
  39. (r"/json", JsonSerializeTestHandler),
  40. (r"/db", QueryTestHandler),
  41. ])
  42. if __name__ == "__main__":
  43. tornado.options.parse_command_line()
  44. application.listen(options.port)
  45. tornado.ioloop.IOLoop.instance().start()