Guest User

Untitled

a guest
Feb 2nd, 2016
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. from random import randint
  3.  
  4. import tornado.concurrent
  5. import tornado.platform.asyncio
  6. import tornado.web
  7.  
  8. from aiopg.sa import create_engine as aiopg_create_engine
  9. import asyncio
  10.  
  11. from models import user
  12.  
  13.  
  14. def asyncio_coroutine(func):
  15. func = asyncio.coroutine(func)
  16.  
  17. def decorator(*args, **kwargs):
  18. future = tornado.concurrent.Future()
  19.  
  20. def future_done(f):
  21. try:
  22. future.set_result(f.result())
  23. except Exception as e:
  24. future.set_exception(e)
  25.  
  26. asyncio.async(func(*args, **kwargs)).add_done_callback(future_done)
  27. return future
  28.  
  29. return decorator
  30.  
  31.  
  32. class BaseHandler(tornado.web.RequestHandler):
  33. def _get_engine(self):
  34. engine = yield from aiopg_create_engine(user='postgres',
  35. database='tornado_chat',
  36. host='127.0.0.1',
  37. password='postgres')
  38. return engine
  39.  
  40. @asyncio.coroutine
  41. def select(self, table_object):
  42. engine = yield from self._get_engine()
  43. with (yield from engine) as conn:
  44. data = yield from conn.execute(table_object)
  45. return data
  46.  
  47. @asyncio.coroutine
  48. def insert(self, table_object):
  49. engine = yield from self._get_engine()
  50. with (yield from engine) as conn:
  51. yield from conn.execute(table_object)
  52.  
  53.  
  54. class MainHandler(BaseHandler):
  55. @asyncio_coroutine
  56. def get(self):
  57. s = randint(0, 7)
  58. # print("in ", '-' * int(s), s)
  59. # yield from asyncio.sleep(s)
  60. # print('out ', '-' * int(s), s)
  61.  
  62. db_messages = yield from self.select(user.select())
  63. db_messages = [{"id": i[0], "name": i[1]} for i in db_messages]
  64. r = yield from self.insert(user.insert().values(name=str(s)))
  65.  
  66. if len(db_messages) > 10:
  67. yield from self.insert(user.delete())
  68. self.render('index.html', messages=db_messages)
  69.  
  70.  
  71. class Application(tornado.web.Application):
  72. def __init__(self):
  73. handlers = (
  74. (r'/', MainHandler),
  75. )
  76.  
  77. tornado.web.Application.__init__(self, handlers)
  78.  
  79.  
  80. application = Application()
  81.  
  82. if __name__ == '__main__':
  83. tornado.platform.asyncio.AsyncIOMainLoop().install()
  84. application.listen(8001)
  85. asyncio.get_event_loop().run_forever()
Add Comment
Please, Sign In to add comment