Projet de remplacement du "RPiPasserelle" d'Otec.
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

db.py 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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. logger.debug(query, 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:
  57. print('failed')
  58. return []
  59. except sqlite3.IntegrityError as e:
  60. print(e)
  61. return []
  62. except sqlite3.OperationalError as e:
  63. raise Exception('Can\'t find DB file %s'.format(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 ? LIKE ?", (key, attr))
  75. res = []
  76. for row in DB.sql(*q):
  77. res.append(res)
  78. return res