def read_temp_and_humidity(self):
     hostname = socket.gethostname()
     while True:
         humidity, temperature = Adafruit_DHT.read_retry(11, 17)
         log.debug('Temp: {0:0.1f} C  Humidity: {1:0.1f} %'.format(
             temperature, humidity))
         self.insert_humidity_to_database(humidity, hostname)
         self.insert_temp_to_database(temperature, hostname)
         self.post_data_to_main_server()
         time.sleep(60)
 def post_data_to_main_server(self):
     payload = self.get_data_from_database_to_send(DBPUSHLIMIT)
     attempts = 0
     success = False
     log.debug("Uploading data")
     while attempts < 3 and not success:
         try:
             r = requests.post(UPLOAD_ADRESS, data={'payload': payload})
             if r.status_code == requests.codes.ok:
                 success = True
                 id = r.json()['data']
                 id_decoded = json.loads(id[0])
                 id_list = []
                 for single_id in id_decoded:
                     id_list.append(single_id['sensor_id_child'])
                 self.database.delete(
                     'sensor_records',
                     'sensor_id in {}'.format(tuple(id_list)))
         except requests.exceptions.ConnectionError:
             time.sleep(10)
             attempts += 1
             log.debug("Error uploading data")
Пример #3
0
def global_router(controlerName='index', actionName='index'):
    file_path = os.path.join(os.getcwd(), 'controllers')
    # lista plikow w katalogu
    file_name = [f for f in os.listdir(file_path) if os.path.isfile(os.path.join(file_path, f))]
    # lista nazw z katalou bez Controller.py
    file_name_cut = ' '.join(file_name).replace('Controller.py', '').split()

    if controlerName in file_name_cut:
        controller_path = controlerName + 'Controller.py'
        controller_full_name = controlerName + 'Controller'

        if os.path.isfile(os.path.join(os.getcwd(), 'controllers', controller_path)):
            module_name = 'controllers.' + controller_full_name
            module = importlib.import_module(module_name, package=controller_full_name)
            controller_instance = getattr(module, controller_full_name)()

            if not hasattr(controller_instance, '__class__'):
                log.debug('Controller {} nie posiada klasy o takiej samej nazwie'.format(controller_full_name))
            action_full_name = actionName + '_action'

            if hasattr(controller_instance, action_full_name):
                log.debug('Controller {} posiada akcje {}'.format(controller_full_name, actionName))

                controller_action = getattr(controller_instance, actionName + '_action')

                if callable(controller_action):
                    log.debug('Controller {}, posiada akcje {}, ktora moze byc wywolana'.format(controller_full_name,
                                                                                                actionName))
                    response = controller_action()
                    if not isinstance(response, list):
                        response = [response]
                    return response_template(description='istnieje strona {}/{}'.format(controlerName, actionName),
                                             data=response)
                else:
                    log.debug('Controller {}, nie posiada akcji {}, jest to atrybut '.format(controller_full_name,
                                                                                             actionName))
            else:
                print 'Controller {} nie posiada akcji {}'.format(controller_full_name, actionName)

                return response_template(description='nie istnieje strona {}/{}'.format(controlerName, actionName),
                                         data=[actionName])

            return response_template(description='istnieje strona {}/{}'.format(controlerName, actionName),
                                     data=[actionName])
        else:
            print ('Controller o takiej nazwie nie istnieje: [{}]'.format(controlerName))
    else:
        return response_template(description='nie istnieje strona {}/{}'.format(controlerName, actionName),
                                 data=[actionName])
Пример #4
0
    def delete(self, table_name, where):
        """

        :param table_name: nazwa tabeli
        :type table_name: str
        :param where: jest warunkiem wykonywania naszego delete
        :type where: str
        :return:
        """
        log.debug("Start of SQL DELETE query...")
        sql = 'DELETE from {} WHERE {}'.format(table_name, where)
        log.debug("Deleting data from database...")
        self.c.execute(sql)
        self.conn.commit()
        log.debug("Success!")
Пример #5
0
    def update(self, table_name, dane, where):
        """

        :param table_name: nazwa tabeli
        :type table_name: str
        :param dane: dane zapisane w dict
        :type dane: dict
        :param where: jest warunkiem wykonywania naszego update
        :type where: str
        """
        log.debug("Start of SQL UPDATE query...")
        sql = u"UPDATE {} SET {} WHERE {}".format(
            table_name, u", ".join(u"{} = '{}'".format(key, values)
                                   for key, values in dane.iteritems()), where)
        log.debug("Updating data in database...")
        self.c.execute(sql)
        self.conn.commit()
        log.debug("Success!")
Пример #6
0
    def select(self, sql):
        """
        :param sql: typ danych wejsciowych
        :type sql: str
        :rtype tuple
        :return:
        """

        log.debug("Start of anti injection sql method...")
        regex = r"\s*SELECT.*"
        matches = re.match(regex, sql, re.MULTILINE | re.IGNORECASE)
        if not matches:
            raise Exception(
                'Pytanie do bazy nie jest wlasciwe: {}'.format(sql))
        log.debug("Selecting data from database...")
        self.c.execute(sql)
        self.conn.commit()
        log.debug("Success!")
        return self.c.fetchall()
Пример #7
0
    def insert(self, table_name, data):
        """

        :param table_name: nazwa tabeli
        :type table_name: str
        :param data: dane zapisane w dict lub liscie
        :type data: dict or list
        :return: zwraca nam ostatni id wrzucony do bazy danych
        :rtype: str
        """
        log.debug("Start of INSERT class... ")
        if isinstance(data, list):
            log.debug(
                "Start of SQL INSERT query that transform list of dict into tuple class..."
            )
            sql = u"INSERT INTO {} ({}) VALUES ({})".format(
                table_name, u",".join(key for key in data[0].keys()),
                u", ".join(u"?".format(v) for v in data[0].values()))
            log.debug("Start of anti injection sql method...")
            regex = r"\s*INSERT.*"
            matches = re.match(regex, sql, re.MULTILINE | re.IGNORECASE)
            if not matches:
                raise Exception(
                    'Pytanie do bazy nie jest wlasciwe: {}'.format(sql))
            listaprzebojow = []  # lista do zapisu tuple
            zmienna_val2 = None
            log.debug(
                "start of validating and transforming list of dict to tuple..."
            )
            for item_index in data:  # robisz fora do danych i go iterujesz
                tuple_wyc = tuple(item_index.values())
                zmienna_valid = len(tuple_wyc)
                self.validateSQL(zmienna_valid, zmienna_val2)
                zmienna_val2 = zmienna_valid
                listaprzebojow.append(
                    tuple_wyc
                )  # dodajesz do listy przerobionego tupla ziterowanego forem wyzej
            log.debug("Inserting data into database...")
            log.debug(sql)
            self.c.executemany(sql, listaprzebojow)
            self.conn.commit()
            log.debug("Success!")
            return True
        else:
            log.debug("Start of SQL INSERT query for dict types...")
            sql = u"INSERT INTO {} ({}) VALUES ({})".format(
                table_name, u", ".join(key for key in data.keys()),
                u", ".join(u'"{}"'.format(v) for v in data.values()))
            log.debug("Start of anti injection sql method...")
            regex = r"\s*INSERT.*"
            matches = re.match(regex, sql, re.MULTILINE | re.IGNORECASE)
            if not matches:
                raise Exception(
                    'Pytanie do bazy nie jest wlasciwe: {}'.format(sql))
            log.debug("Inserting data into database...")
            log.debug(sql)
            self.c.execute(sql)
            self.conn.commit()
            log.debug("Success!")
            return self.c.lastrowid