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.2KB

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