Projet de remplacement du "RPiPasserelle" d'Otec.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

db.py 1.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #!/usr/bin/env python3
  2. import sqlite3
  3. from subprocess import Popen
  4. from .config import config
  5. import sys
  6. from pprint import pprint
  7. from pyheatpump.logger import logger_init
  8. logger = logger_init()
  9. conn = None
  10. def connect():
  11. global conn
  12. if conn is None:
  13. logger.info('Will connect to database {}'.format(
  14. config['heatpump']['database']))
  15. conn = sqlite3.connect(config['heatpump']['database'])
  16. conn.row_factory = sqlite3.Row
  17. return conn
  18. def commit():
  19. global conn
  20. logger.info('Commit database')
  21. conn.commit()
  22. def initialize(filename):
  23. p = Popen(
  24. '/usr/bin/env sqlite3 -init {} {}'.format(filename, config['heatpump']['database']),
  25. shell=True
  26. )
  27. return True if p.wait() == 0 else False
  28. def sql(query):
  29. global conn
  30. if conn is None:
  31. connect()
  32. cursor = conn.cursor()
  33. logger.debug(f'Will execute query : \n{query}\n')
  34. cursor.execute(query)
  35. return cursor
  36. class RowClass(object):
  37. def __init__(self, **kwargs):
  38. for key in kwargs.keys():
  39. if hasattr(self, key):
  40. setattr(self, key, kwargs[key])
  41. def select(self, key, tablename):
  42. attr = getattr(self, key)
  43. if type(attr) == str:
  44. q = f"SELECT * FROM {tablename} WHERE {key} LIKE '{attr}'"
  45. elif type(attr) == int:
  46. q = f"SELECT * FROM {tablename} WHERE {key} = {attr}"
  47. return sql(q)