Advertisement
Guest User

Untitled

a guest
Oct 14th, 2016
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. from psycopg2.pool import SimpleConnectionPool
  2. import gevent_psycopg2
  3.  
  4. gevent_psycopg2.monkey_patch()
  5.  
  6. class BaseHandler(web.RequestHandler):
  7.  
  8. @property
  9. def db(self):
  10. if not hasattr(self.application, 'pgpool'):
  11. self.application.pgpool = SimpleConnectionPool(minconn=1, maxconn=20,host='localhost', database='database', user='postgres',
  12. password='password', port=5432)
  13.  
  14. if not hasattr(self, '_db'):
  15. self._db = self.application.pgpool.getconn()
  16. return self._db
  17.  
  18. def set_status(self, status_code):
  19. '''
  20. 解决因为数据库操作错误导致的全局500错误
  21. '''
  22. if status_code == 500:
  23. self.db.rollback()
  24. super(BaseHandler, self).set_status(status_code)
  25.  
  26. def get(self):
  27. cur = self.db.cursor()
  28. cur.execute('select * from articles')
  29. self.write(str(cur.fetchall()))
  30.  
  31. def on_finish(self):
  32. self.application.pgpool.putconn(self.db)#将数据库连接放回连接池中
  33. del self._db
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement