server.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import random
  2. import sys
  3. from bson import ObjectId
  4. import json
  5. import motor
  6. import tornado.ioloop
  7. import tornado.web
  8. from tornado import gen, escape
  9. import tornado.options
  10. from tornado.options import options
  11. import tornado.httpserver
  12. PY3 = False
  13. if sys.version_info[0] == 3:
  14. PY3 = True
  15. xrange = range
  16. tornado.options.define('port', default=8888, type=int, help="Server port")
  17. tornado.options.define('mongo', default='localhost', type=str, help="MongoDB host")
  18. class BaseHandler(tornado.web.RequestHandler):
  19. def compute_etag(self):
  20. return None
  21. class JsonSerializeTestHandler(BaseHandler):
  22. def get(self):
  23. obj = dict(message="Hello, World!")
  24. self.write(obj)
  25. class PlaintextHandler(BaseHandler):
  26. def get(self):
  27. self.set_header('Content-Type', 'text/plain')
  28. self.write(b"Hello, World!")
  29. class QueryTestHandler(BaseHandler):
  30. @tornado.web.asynchronous
  31. @gen.coroutine
  32. def get(self):
  33. queries = int(self.get_argument("queries", 0))
  34. if queries == 0:
  35. random_id = random.randint(1, 10000)
  36. world = yield motor.Op(db.world.find_one, random_id)
  37. # Get first postion on arguments, and so first postion in mongo return
  38. world['id'] = world.pop('_id')
  39. response = json.dumps(world)
  40. else:
  41. worlds = []
  42. for i in xrange(int(queries)):
  43. random_id = random.randint(1, 10000)
  44. world = yield motor.Op(db.world.find_one, random_id)
  45. # Get first postion on arguments, and so first postion in mongo return
  46. world['id'] = world.pop('_id')
  47. worlds.append(world)
  48. response = json.dumps(worlds)
  49. self.set_header("Content-Type", "application/json; charset=UTF-8")
  50. self.finish(response)
  51. application = tornado.web.Application([
  52. (r"/json", JsonSerializeTestHandler),
  53. (r"/plaintext", PlaintextHandler),
  54. (r"/db", QueryTestHandler),
  55. ])
  56. if __name__ == "__main__":
  57. tornado.options.parse_command_line()
  58. server = tornado.httpserver.HTTPServer(application)
  59. server.bind(options.port)
  60. server.start(0)
  61. db = motor.MotorClient(options.mongo).open_sync().hello_world
  62. tornado.ioloop.IOLoop.instance().start()