Advertisement
Davitkova

pg_con_with_pool

Feb 19th, 2025
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.12 KB | None | 0 0
  1. from psycopg2 import pool
  2.  
  3.  
  4. class PostgresConnectionPool( pool.SimpleConnectionPool ):
  5.  
  6.     def __init__( self, init_con_number, max_con_number, host, port, database, user, password ):
  7.  
  8.         # initialize the Postgresql connection pool object
  9.         super().__init__( minconn=init_con_number,
  10.                           maxconn=max_con_number,
  11.                           host=host,
  12.                           port=port,
  13.                           database=database,
  14.                           user=user,
  15.                           password=password )
  16.    
  17.    
  18.     def get_con_from_pool( self ):
  19.         return self.getconn()
  20.  
  21.     def put_con_back_to_pool( self, con):
  22.         self.putconn(con)
  23.  
  24.  
  25. # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
  26. # Example how pool will look:
  27. # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
  28.  
  29. def print_pool_state( name, pool: PostgresConnectionPool):
  30.  
  31.     print(f"\n===============================\nPool {name} state:\n===============================\n")
  32.     for p, v in pool.__dict__.items():
  33.         if p == '_pool':
  34.             print('_pool connections at instantiation')
  35.             [print(f"  {obj}") for obj in v]
  36.             continue
  37.         print(p, v)
  38.  
  39.  
  40. my_pool_2 = PostgresConnectionPool('2', '5','192.168.144.13' ,5432,'softuni_management_db', 'test_name', 'test_pass')
  41. print_pool_state( 'my_pool_2', my_pool_2)
  42.  
  43. # Get free connections from the pool:
  44. my_connection_1 = my_pool_2.get_con_from_pool()
  45. my_connection_2 = my_pool_2.get_con_from_pool()
  46. my_connection_3 = my_pool_2.get_con_from_pool()
  47. my_connection_4 = my_pool_2.get_con_from_pool()
  48. my_connection_5 = my_pool_2.get_con_from_pool()
  49. print_pool_state( 'my_pool_2', my_pool_2)
  50.  
  51. try:
  52.     unsuccessful_con = my_pool_2.get_con_from_pool()
  53. except Exception as e:
  54.     print(f"\n===============================\n"
  55.           f"Pool {my_pool_2.__class__.__name__} state:\n"
  56.           f"===============================\n{e}")
  57.  
  58. my_pool_2.put_con_back_to_pool(my_connection_1)
  59. print_pool_state( 'my_pool_2', my_pool_2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement