Legend:
- Unmodified
- Added
- Removed
-
db.py
r95cf703 r527c097 1 1 import datetime 2 2 import psycopg2 3 from psycopg2 import pool 4 from contextlib import contextmanager 3 5 4 6 DB_CONFIG = { … … 11 13 } 12 14 15 # -- Connection Pool ---------------------------------------------------------- 16 # Reuses database connections instead of opening a new one per query. 17 # SimpleConnectionPool maintains between minconn and maxconn connections. 13 18 19 _pool = None 20 21 22 def _get_pool(): 23 global _pool 24 if _pool is None: 25 _pool = pool.SimpleConnectionPool(minconn=2, maxconn=10, **DB_CONFIG) 26 return _pool 27 28 29 @contextmanager 14 30 def get_connection(): 15 return psycopg2.connect(**DB_CONFIG) 31 """Get a read-only connection from the pool. 32 Autocommit is enabled so SELECTs don't need explicit commit. 33 Connection is returned to the pool on exit.""" 34 p = _get_pool() 35 conn = p.getconn() 36 try: 37 conn.autocommit = True 38 yield conn 39 finally: 40 conn.autocommit = False 41 p.putconn(conn) 42 43 44 @contextmanager 45 def get_transaction(): 46 """Get a connection with explicit transaction management. 47 Commits on successful exit, rolls back on exception. 48 Connection is returned to the pool in both cases.""" 49 p = _get_pool() 50 conn = p.getconn() 51 try: 52 conn.autocommit = False 53 yield conn 54 conn.commit() 55 except Exception: 56 conn.rollback() 57 raise 58 finally: 59 p.putconn(conn) 60 61 62 def close_pool(): 63 """Close all connections in the pool.""" 64 global _pool 65 if _pool is not None: 66 _pool.closeall() 67 _pool = None 68 69 70 # -- UI Helpers --------------------------------------------------------------- 16 71 17 72
Note:
See TracChangeset
for help on using the changeset viewer.
