Advertisement
Guest User

Untitled

a guest
Nov 2nd, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.75 KB | None | 0 0
  1. from urllib.parse import urlparse
  2. import psycopg2
  3.  
  4. import sqlalchemy
  5. from testcontainers.postgres import PostgresContainer
  6.  
  7. psql_config = {
  8.     'database': 'test',
  9.     'user': 'test',
  10.     'password': 'test',
  11.     'host': '127.0.0.1',
  12.     'port': '5432',
  13. }
  14.  
  15.  
  16. class Cursor(object):
  17.     def __init__(self, sql_config=psql_config, as_dict=True):
  18.         cursor_params = dict()
  19.         if as_dict:
  20.             cursor_params['cursor_factory'] = psycopg2.extras.RealDictCursor
  21.         self.connection = psycopg2.connect(**sql_config)
  22.         self.cursor = self.connection.cursor(**cursor_params)
  23.  
  24.     def __iter__(self):
  25.         for item in self.cursor:
  26.             yield item
  27.  
  28.     def __enter__(self):
  29.         return self.cursor
  30.  
  31.     def __exit__(self, ext_type, exc_value, traceback):
  32.         self.cursor.close()
  33.         if isinstance(exc_value, Exception):
  34.             self.connection.rollback()
  35.         else:
  36.             self.connection.commit()
  37.         self.connection.close()
  38.  
  39.  
  40. def extract_config_from_url(url):
  41.     result = urlparse(url)
  42.     config = dict(
  43.         user = result.username,
  44.         password = result.password,
  45.         database = result.path[1:],
  46.         host = result.hostname,
  47.         port = result.port,
  48.     )
  49.     return config
  50.  
  51. def test_docker_run_postgress():
  52.     postgres_container = PostgresContainer("postgres:9.5")
  53.     with postgres_container as postgres:
  54.         url = postgres.get_connection_url()
  55.         config = extract_config_from_url(url)
  56.         with Cursor(config) as c:
  57.             c.execute('select 5')
  58.             print(c.fetchone())
  59. #        e = sqlalchemy.create_engine(postgres.get_connection_url())
  60. #_       result = e.execute("select version()")
  61.     print('a')
  62.  
  63. test_docker_run_postgress()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement