server.py 1.8 KB

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