-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdbpool.py
More file actions
65 lines (50 loc) · 1.43 KB
/
dbpool.py
File metadata and controls
65 lines (50 loc) · 1.43 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/usr/bin/env python
# coding=utf-8
"""wrap psycopg2 threaded connection pool using contextmanager.
see example usage in test_pool.py
"""
import os
from contextlib import contextmanager
import psycopg2.pool
import psycopg2.extras
POOL = None
CONF = {
"db.poolmin": os.getenv('DBPOOLMIN', "3"),
"db.poolmax": os.getenv('DBPOOLMAX', "10"),
"db.host": os.getenv('PGHOST', "localhost"),
"db.port": os.getenv('PGPORT', "5432"),
"db.name": os.getenv('PGDATABASE', "t1"),
"db.user": os.getenv('PGUSER', "t1"),
"db.password": os.getenv('PGPASSWORD', "fNfwREMqO69TB9YqE+/OzF5/k+s="),
}
def _get_pool():
global POOL
if not POOL:
POOL = psycopg2.pool.ThreadedConnectionPool(
int(CONF.get("db.poolmin")),
int(CONF.get("db.poolmax")),
host=CONF.get("db.host"),
port=int(CONF.get("db.port")),
database=CONF.get("db.name"),
user=CONF.get("db.user"),
password=CONF.get("db.password"))
return POOL
@contextmanager
def get_conn():
conn = _get_pool().getconn()
try:
yield conn
conn.commit()
except:
conn.rollback()
raise
finally:
POOL.putconn(conn)
@contextmanager
def get_cursor():
with get_conn() as conn:
yield conn.cursor()
@contextmanager
def get_dict_cursor():
with get_conn() as conn:
yield conn.cursor(cursor_factory=psycopg2.extras.DictCursor)