Guest User

Untitled

a guest
Aug 13th, 2018
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.67 KB | None | 0 0
  1. pool = ThreadedConnectionPool(
  2. 1, 20, database=url.path,
  3. user=url.username,
  4. password=url.password,
  5. host=url.hostname,
  6. port=url.port
  7. )
  8.  
  9. @contextmanager
  10. def db_connection():
  11. try:
  12. con = pool.getconn()
  13. yield con
  14. finally:
  15. pool.putconn(con)
  16.  
  17.  
  18. @contextmanager
  19. def db_cursor(commit=False):
  20. with db_connection() as con:
  21. cur = con.cursor(cursor_factory=RealDictCursor)
  22. try:
  23. yield cur
  24. if commit:
  25. con.commit()
  26. except psycopg2.DatabaseError as e:
  27. logging.getLogger(__name__).error('Error during using db: %s', e)
  28. con.rollback()
  29. finally:
  30. cur.close()
Add Comment
Please, Sign In to add comment