Projet de remplacement du "RPiPasserelle" d'Otec.
Ви не можете вибрати більше 25 тем Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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