Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from psycopg2.pool import SimpleConnectionPool
- import gevent_psycopg2
- gevent_psycopg2.monkey_patch()
- class BaseHandler(web.RequestHandler):
- @property
- def db(self):
- if not hasattr(self.application, 'pgpool'):
- self.application.pgpool = SimpleConnectionPool(minconn=1, maxconn=20,host='localhost', database='database', user='postgres',
- password='password', port=5432)
- if not hasattr(self, '_db'):
- self._db = self.application.pgpool.getconn()
- return self._db
- def set_status(self, status_code):
- '''
- 解决因为数据库操作错误导致的全局500错误
- '''
- if status_code == 500:
- self.db.rollback()
- super(BaseHandler, self).set_status(status_code)
- def get(self):
- cur = self.db.cursor()
- cur.execute('select * from articles')
- self.write(str(cur.fetchall()))
- def on_finish(self):
- self.application.pgpool.putconn(self.db)#将数据库连接放回连接池中
- del self._db
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement