Projet de remplacement du "RPiPasserelle" d'Otec.
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

db.py 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. #!/usr/bin/env python3
  2. import sqlite3
  3. from subprocess import Popen
  4. from .config import config
  5. import sys
  6. from pyheatpump.logger import logger_init
  7. logger = logger_init()
  8. conn = None
  9. class DB():
  10. Conn = None
  11. @staticmethod
  12. def connect():
  13. if DB.Conn:
  14. try:
  15. DB.Conn.cursor()
  16. return True
  17. except sqlite3.ProgrammingError:
  18. pass
  19. except Exception as e:
  20. logger.error('DB.connect: %s', e)
  21. sys.exit(1)
  22. logger.info('Will connect to database {}'.format(
  23. config['heatpump']['database']))
  24. DB.Conn = sqlite3.connect(
  25. config['heatpump']['database'],
  26. isolation_level=None)
  27. DB.Conn.row_factory = sqlite3.Row
  28. return True
  29. def commit(self):
  30. """
  31. Default mode of connecting is autocommit
  32. """
  33. pass
  34. @staticmethod
  35. def initialize(filename):
  36. if DB.Conn:
  37. DB.Conn.close()
  38. p = Popen(
  39. '/usr/bin/env sqlite3 -init {} {}'.format(filename, config['heatpump']['database']),
  40. shell=True)
  41. return True if p.wait() == 0 else False
  42. @staticmethod
  43. def sql(query, params={}):
  44. logger.debug('Query : %s', query)
  45. logger.debug('Params : %s', params)
  46. if not DB.connect():
  47. raise Exception('Can\'t connect to DB')
  48. return DB.Conn.execute(query, params or {})
  49. @staticmethod
  50. def sqlf(filename):
  51. with open(filename) as f:
  52. if not DB.connect():
  53. raise Exception('Can\'t connect to DB')
  54. try:
  55. return DB.Conn.execute((' '.join(f.readlines())).replace('\n', ''))
  56. except StopIteration as e:
  57. logger.error('sqlf(%s): %s', filename, e)
  58. return []
  59. except sqlite3.IntegrityError as e:
  60. logger.error('sqlf(%s): %s', filename, e)
  61. return []
  62. except sqlite3.OperationalError as e:
  63. raise Exception(f'Can\'t find DB file {filename}') from e
  64. class RowClass(object):
  65. def __init__(self, **kwargs):
  66. for key in kwargs.keys():
  67. if hasattr(self, key):
  68. setattr(self, key, kwargs[key])
  69. def select(self, key, tablename):
  70. attr = getattr(self, key)
  71. if type(attr) == str:
  72. q = ("SELECT * FROM {tablename} WHERE ? LIKE '?'", (key, attr))
  73. elif type(attr) == int:
  74. q = ("SELECT * FROM {tablename} WHERE ? = ?", (key, attr))
  75. res = []
  76. for row in DB.sql(*q):
  77. res.append(res)
  78. return res