文章目录

前段时间找到一个叫momoko的可以实现这个功能,但使用上出了点问题,对于子函数的调用会出现顺利不正常,后来看看了psycopg2的文档,里面提到psycopg2是有异步支持的,还可以通过写一个wait函数来处理,文档里面提到的是用select,后来在pypi上找到一个使用gevent的 gevent-psycopg2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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
文章目录