Advertisement
Guest User

Untitled

a guest
Jul 16th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.48 KB | None | 0 0
  1. import os
  2. import psycopg2.pool
  3.  
  4. connection_pool = psycopg2.pool.ThreadedConnectionPool(0, 50,
  5.     dbname='foobar',
  6.     user='foobar',
  7.     password='foobar',
  8.     host=HOST,
  9.     )
  10.  
  11. class db_conn(object):
  12.     def execute(self, query, params=()):
  13.         self.cur.execute(query, params)
  14.     def execute_fetch(self, query, params=()):
  15.         self.cur.execute(query, params)
  16.         return self.cur.fetchall()
  17.     def execute_fetchone(self, query, params=()):
  18.         self.cur.execute(query, params)
  19.         return self.cur.fetchone()
  20.     def execute_fetch_dict(self, query, params=()):
  21.         self.cur.execute(query, params)
  22.         rows = self.cur.fetchall()
  23.         columns = [d[0] for d in self.cur.description]
  24.         dict_rows = [dict(zip(columns, row)) for row in rows]
  25.         return dict_rows
  26.     def execute_fetchone_dict(self, query, params=()):
  27.         self.cur.execute(query, params)
  28.         row = self.cur.fetchone()
  29.         if row:
  30.             columns = [d[0] for d in self.cur.description]
  31.             dict_row = dict(zip(columns, row))
  32.             return dict_row
  33.     def row_count(self):
  34.         return self.cur.rowcount
  35.  
  36.     def __enter__(self):
  37.         self.conn = connection_pool.getconn()
  38.         self.cur = self.conn.cursor()
  39.         return self
  40.    
  41.     def __exit__(self, type, value, traceback):
  42.         if type is None:
  43.             self.conn.commit()
  44.         self.cur.close()
  45.         self.conn.rollback()
  46.         connection_pool.putconn(self.conn)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement