Guest User

Untitled

a guest
Mar 16th, 2016
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. import sys
  2. import tornado.ioloop
  3. import psycopg2
  4. import psycopg2.extensions
  5.  
  6. io_loop = tornado.ioloop.IOLoop.instance()
  7. conn = psycopg2.connect('dbname=mytest user=lbolla password=secret')
  8. conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
  9.  
  10.  
  11. def listen(ch):
  12. '''Listen to a channel.'''
  13. curs = conn.cursor()
  14. curs.execute("LISTEN %s;" % ch)
  15.  
  16.  
  17. def receive(fd, events):
  18. '''Receive a notify message from the channel we are listening.'''
  19. state = conn.poll()
  20. if state == psycopg2.extensions.POLL_OK:
  21. if conn.notifies:
  22. notify = conn.notifies.pop()
  23. print(notify.payload)
  24. io_loop.add_handler(conn.fileno(), receive, io_loop.READ)
  25.  
  26.  
  27. def talk(who, ch):
  28. # Connections are thread-safe, but cursors are not
  29. curs = conn.cursor()
  30.  
  31. def _talk():
  32. while True:
  33. what = input()
  34. msg = '[%s] %s: %s' % (ch, who, what)
  35. # Notify all of what you just said
  36. curs.execute("NOTIFY %s, '%s';" % (ch, msg))
  37. # Run in a separate thread: we could also monitor stdin into the IOLoop...
  38. threading.Thread(target=_talk).start()
  39.  
  40.  
  41. if __name__ == '__main__':
  42. who, ch = sys.argv[1:3]
  43. # Always listen before talk!
  44. listen(ch)
  45. talk(who, ch)
  46. io_loop.start()
Add Comment
Please, Sign In to add comment