Ejemplo n.º 1
0
def main():
    """Функция опрашивает API раз в час и загружает данные в бд"""
    
    startDateURL = (datetime.now() - timedelta(days=3) ).strftime("%Y-%m-%d")
    endDateURL = (datetime.now() - timedelta(days=1) ).strftime("%Y-%m-%d")

    URL = "https://www.ncei.noaa.gov/" + \
    "access/services/data/v1?" + \
    "dataset=local-climatological-data&" + \
    "stations=72509014739&" + \
    "units=metric&" + \
    f"startDate={startDateURL}&endDate={endDateURL}&" + \
    "format=json"

    # запрос к погодной api
    r = requests.get(URL)
    request_json = r.json()

    try:
        # Сохранение в переменную данных за последний доступный час
        last_hour_values = request_json[-1]
    except IndexError:
        # Выход тк нет данных
        return
        
    #получение всех данных от нужного датчика
    FM_15_current_day_list = []
    for FM_15_values in request_json:
        if FM_15_values['REPORT_TYPE'] == 'FM-15':
            FM_15_current_day_list.append(FM_15_values)

    # вывод значений последнего доступного часа            
    last_hour_values = FM_15_current_day_list[-1]
    current_date = datetime.strptime(last_hour_values['DATE'] + '+03:00', '%Y-%m-%dT%H:%M:%S%z')
    hourly_humidity = float(last_hour_values['HourlyRelativeHumidity'])
    hourly_temp = float(last_hour_values['HourlyDryBulbTemperature'])
    hourly_pressure = float(last_hour_values['HourlyStationPressure'])*25.4

    db_conn = Database()

    try:
        last_date = db_conn.select("""
                                      SELECT date FROM dashboard_weather
                                      ORDER BY date DESC LIMIT 5
                                   """)[0][0]
    except IndexError:
        last_date = False

    # условие для проверки повторений
    if last_date != current_date:
        db_conn.add("""
                        INSERT INTO dashboard_weather
                        (humidity, pressure, temp, date)
                        VALUES (%s, %s, %s, %s)
                    """, (hourly_humidity, hourly_pressure, hourly_temp, current_date))

    db_conn.close()
Ejemplo n.º 2
0
import time
import Adafruit_DHT
from db_conn import Database

DHT_SENSOR = Adafruit_DHT.DHT22
DHT_PIN = 4

database = Database()

while True:
    humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)

    if humidity is not None and temperature is not None:
        database.insert_dht22(data=time.strftime('%Y-%m-%d'),
                              hora=time.strftime('%H:%M:%S'),
                              umidade=humidity,
                              temperatura=temperature)
    else:
        print("falha ao coletar dados do sensor")

    time.sleep(60)
Ejemplo n.º 3
0
from tkinter import *
import tkinter.messagebox as tkmsgbox
from db_conn import Database
import validation

db = Database('contacts.db')

root = Tk()
root.title("Contacts")
root.geometry("430x250")

#=-=-=-=-=-=Frames=-=-=-=-=-=-=
tops = Frame(root)
tops.pack(side=TOP)

bot = Frame(root)
bot.pack(side=BOTTOM)

#=-=-=-=-=-=-Variables=-=-=-=-=-=-=
fname = StringVar()
lname = StringVar()
mob = StringVar()
email = StringVar()

#=-=-=-=--=-=-=-=Functions=-=-=-=-=-=-=-=
def content():
    lst.delete(0, END)
    for row in db.fetch():
        lst.insert(END, row)

def select(row):
Ejemplo n.º 4
0
 def __init__(self):
     self.database = Database()
     self.database.create_user_table()
Ejemplo n.º 5
0
from db_conn import Database
from datetime import datetime, timedelta
import random

db_conn = Database()

now = datetime.now()

for days in range(7, 500):

    for hours in range(1, 2):
        hourly_humidity = random.randint(40, 61)
        hourly_pressure = random.randint(780, 891)
        hourly_temp = random.randint(10, 27)
        new_date = now - timedelta(days=days, hours=hours)

        db_conn.add(
            """
	    	            INSERT INTO dashboard_weather
	       	        	(humidity, pressure, temp, date)
	           	    	VALUES (%s, %s, %s, %s)
		            """, (hourly_humidity, hourly_pressure, hourly_temp, new_date))

db_conn.close()
Ejemplo n.º 6
0
 def setUp(self):
     """Initialisez app and defines variables"""
     app.testing = True
     self.tester = app.test_client()
     self.database = Database()
     self.database.create_user_table()