[annuaires_pg] lazy conn à la base pg

Beaucoup de scripts (via le binding) importent ce fichier et ne
s'en servent en pratique que très rarement, on effectue donc
une connexion à la base pg uniquement lors de l'appel aux fonctions
le nécessitant.
This commit is contained in:
Daniel STAN 2013-04-05 18:00:07 +02:00
parent 092f355074
commit 88ba72332a

View file

@ -2,27 +2,29 @@
# -*- coding: utf-8 -*-
import psycopg2
from functools import wraps
try:
if __name__ == 'annuaires_pg_test':
conn = psycopg2.connect(user='crans', database='switchs', host='localhost')
else:
conn = psycopg2.connect(user='crans', database='switchs', host='pgsql.adm.crans.org')
# Population de la tâble avec les bâtiments
cur = conn.cursor()
cur.execute("SELECT DISTINCT batiment FROM prises")
bat_switchs = [i[0] for i in cur.fetchall()]
cur.close()
del cur
except psycopg2.OperationalError:
bat_switchs = ["a", "b", "c", "g", "h", "i", "j", "m", "o", "p"]
conn = None
def _need_conn(f):
"""Décorateur à appliquer aux fonctions nécessitant une connexion pgsql"""
@wraps(f)
def first_connect(*args, **kwargs):
global conn
if conn == None:
if __name__ == 'annuaires_pg_test':
host='localhost'
else:
host='pgsql.adm.crans.org'
# "connecting …"
conn = psycopg2.connect(user='crans', database='switchs', host=host)
return f(*args, **kwargs)
return first_connect
bat_switchs = ["a", "b", "c", "g", "h", "i", "j", "m", "o", "p"]
bat_manuels = []
@_need_conn
def chbre_prises(batiment, chambre = None):
"""Correspondance chambre -> prise"""
batiment = batiment.lower()
@ -44,6 +46,7 @@ def chbre_prises(batiment, chambre = None):
raise ValueError("Batiment inexistant")
return ret
@_need_conn
def chbre_commentaire(batiment, chambre):
""" Renvoie le commentaire associé à la chambre """
global conn
@ -55,6 +58,7 @@ def chbre_commentaire(batiment, chambre):
except TypeError:
raise ValueError("Chambre inexistante")
@_need_conn
def reverse(batiment, prise = None):
"""Correspondance prise -> chambre"""
batiment = batiment.lower()
@ -79,6 +83,7 @@ def reverse(batiment, prise = None):
raise ValueError("Batiment inexistant")
return ret
@_need_conn
def is_crans(batiment, chambre):
"""Chambre cablee au Cr@ns ?"""
batiment = batiment.lower()
@ -87,6 +92,7 @@ def is_crans(batiment, chambre):
cur.execute("SELECT crans FROM prises WHERE (batiment, chambre) = (%s, %s)", (batiment, chambre))
return cur.fetchone()[0]
@_need_conn
def is_connected(batiment, chambre):
"""Cablage physique effectue ?"""
batiment = batiment.lower()
@ -95,6 +101,7 @@ def is_connected(batiment, chambre):
cur.execute("SELECT cablage_effectue FROM prises WHERE (batiment, chambre) = (%s, %s)", (batiment, chambre))
return cur.fetchone()[0]
@_need_conn
def crous_to_crans(batiment, chambre):
"""Passage d'une chambre de CROUS a Cr@ns"""
batiment = batiment.lower()