5
0
Fork 0
mirror of https://git.securmail.fr/gizmo/python-module-pgsql.git synced 2024-12-22 08:14:42 +01:00

Maj module

This commit is contained in:
Boris Tassou 2019-12-03 12:12:25 +01:00
parent df68cc8bfb
commit 0810e4cfbb
8 changed files with 52 additions and 18 deletions

View file

@ -12,6 +12,7 @@
# */
import sys
from configparser import SafeConfigParser
# Global name
__version__ = '1.0'
@ -23,3 +24,11 @@ try:
except ImportError:
print('Psycopg2 library not found. Books-shelf cannot start.')
sys.exit(1)
try:
ini_conf = "./config/conf.ini"
config = SafeConfigParser()
config.read(ini_conf)
except config.Error as error:
print(error)
sys.exit(1)

View file

@ -1,5 +0,0 @@
[psql]
host=localhost
database=books_shelf
user=books_shelf
passwd=blabli

View file

@ -0,0 +1,5 @@
[psql]
host=localhost
database=books
user=books_shelf
passwd=blabli

View file

@ -11,9 +11,21 @@
# * ----------------------------------------------------------------------------
# */
import socket
from configparser import SafeConfigParser
import psycopg2
# Read conf.ini
INI_CONF = "./config/conf.ini"
CONFIG = SafeConfigParser()
CONFIG.read(INI_CONF)
# DB parameters
PSQL_HOST = CONFIG.get('psql', 'host')
PSQL_DB = CONFIG.get('psql', 'database')
PSQL_USER = CONFIG.get('psql', 'user')
PSQL_PWD = CONFIG.get('psql', 'passwd')
class HandlePsql:
"""Class to handle psql connection."""
@ -21,28 +33,39 @@ class HandlePsql:
conn = None
cur = None
@staticmethod
def psql_checkport():
"""Check pgsql port."""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
check_port = sock.connect_ex((PSQL_HOST, 5432))
if check_port:
return True
return False
@staticmethod
def psql_checkcon():
"""Check pgsql connexion to database."""
try:
conn = psycopg2.connect(host=PSQL_HOST, database=PSQL_DB,
user=PSQL_USER, password=PSQL_PWD,
connect_timeout=5)
conn.close()
return True
except conn.error:
return False
@staticmethod
def psql_conn():
"""Init psql connection."""
# Read conf.ini
ini_conf = "/usr/local/Securmail-Administration/config/conf.ini"
config = SafeConfigParser()
config.read(ini_conf)
# DB parameters
psql_host = config.get('psql', 'host')
psql_db = config.get('psql', 'database')
psql_user = config.get('psql', 'user')
psql_pwd = config.get('psql', 'passwd')
# connexion DB
# http://initd.org/psycopg/docs/usage.html
# http://www.postgresqltutorial.com/postgresql-python/
try:
global conn
conn = psycopg2.connect(host=psql_host, database=psql_db, user=psql_user, password=psql_pwd)
conn = psycopg2.connect(host=PSQL_HOST, database=PSQL_DB,
user=PSQL_USER, password=PSQL_PWD)
conn.cursor()
except (Exception, psycopg2.DatabaseError) as error:
except psycopg2.DatabaseError as error:
print(error)
@staticmethod
@ -77,9 +100,11 @@ class HandlePsql:
@staticmethod
def psql_unconn():
"""End psql connection."""
global conn
cur = conn.cursor()
cur.close()
conn.close()
if __name__ == "__main__":
print("Module psql to handle the connection")