#!/usr/bin/env python3 import sqlite3 from subprocess import Popen from .conf import config import sys from pprint import pprint conn = None def connect(): global conn if conn is None: print('Will connect to database {}'.format( config['heatpump']['database'])) conn = sqlite3.connect(config['heatpump']['database']) conn.row_factory = sqlite3.Row return conn def initialize(filename): p = Popen( '/usr/bin/env sqlite3 -init {} {}'.format(filename, config['heatpump']['database']), shell=True ) return True if p.wait() == 0 else False def sql(query): global conn if conn is None: connect() pprint(conn) cursor = conn.cursor() print(f'Will execute query : \n{query}\n') cursor.execute(query) return cursor class RowClass(object): def __init__(self, **kwargs): for key in kwargs.keys(): if hasattr(self, key): setattr(self, key, kwargs[key]) def select(self, key, tablename): attr = getattr(self, key) if type(attr) == str: q = f"SELECT * FROM {tablename} WHERE {key} LIKE '{attr}'" elif type(attr) == int: q = f"SELECT * FROM {tablename} WHERE {key} = {attr}" return sql(q)