]> AND Private Git Repository - predictops.git/blob - lib/tools/connector.py
Logo AND Algorithmique Numérique Distribuée

Private GIT Repository
cleaning main.py file
[predictops.git] / lib / tools / connector.py
1 from pathlib import Path
2 import psycopg2
3 import configparser
4
5 class Singleton:
6
7     def __init__(self, cls):
8         self._cls = cls
9
10     def Instance(self):
11         try:
12             return self._instance
13         except AttributeError:
14             self._instance = self._cls()
15             return self._instance
16
17     def __call__(self):
18         raise TypeError('Singletons must be accessed through `Instance()`.')
19
20     def __instancecheck__(self, inst):
21         return isinstance(inst, self._cls)
22     
23 @Singleton
24 class PostgreSQLDBConnection(object):
25     """Postgresql database connection"""
26     
27     def __init__(self, connection_string = ''):
28         if connection_string == '':
29             # We're retrieving information related to the database in config.ini
30             config = configparser.ConfigParser()
31             config.read((Path.cwd() / 'config') / 'main.cfg')
32     
33             host   = config['postgresql']['host']
34             user   = config['postgresql']['user']
35             port   = config['postgresql']['port']
36             self.dbname = config['postgresql']['dbname']
37             
38             self.connection_string = f"host={host} port={port} dbname={self.dbname} user={user}"
39             
40         else:
41             self.connection_string = connection_string
42             self.dbname = ''
43
44             
45     def __enter__(self):
46         self.connection = psycopg2.connect(self.connection_string)
47         self.connection.autocommit = True
48         self.cursor = self.connection.cursor()
49         return self
50
51     @property   
52     def name(self):
53         return self.dbname
54     
55     def __str__(self):
56         return 'Database connection object'
57     
58     def __exit__(self, exc_type, exc_val, exc_tb):
59         #self.connection.commit()
60         self.cursor.close()
61         self.connection.close()        
62