Получить запрос - цикл Python - PullRequest
0 голосов
/ 31 января 2019

как я могу получать данные из openweather api каждые X минут?Я хочу отобразить эти данные на 16x2 ЖК-дисплее с помощью Raspberry Pi Zero W.

import lcddriver
import time
import datetime
import requests, json 

display = lcddriver.lcd()
complete_url = "http://api.openweathermap.org/data/2.5/weather?q=CITY&APPID=****HIDE_API*****" 

response = requests.get(complete_url)

x = response.json() 


if x["cod"] != "404": 

    y = x["main"] 

    current_temperature = y["temp"] 


    current_pressure = y["pressure"] 


    current_humidiy = y["humidity"] 




    z = x["weather"] 


    weather_description = z[0]["description"] 
try:


        print("Writing to display")
        display.lcd_display_string("Temperatura zew:",1) 
        display.lcd_display_string(str(current_temperature-273.15) + " C", 2) 
        time.sleep(10)  
        display.lcd_clear()                                   
        display.lcd_display_string("Cisnienie ", 1)
        display.lcd_display_string(str(current_pressure) + " hPa",2) 
        time.sleep(10) 
        display.lcd_clear()
        display.lcd_display_string("Wilgotnosc ", 1)
        display.lcd_display_string(str(current_humidiy) + " %",2)
        time.sleep(10)                                    
        display.lcd_clear()                             
        time.sleep(1)                                    

except KeyboardInterrupt: # If there is a KeyboardInterrupt (when you press ctrl+c), exit the program and cleanup
    print("Cleaning up!")
    display.lcd_clear()

Ответы [ 3 ]

0 голосов
/ 31 января 2019

Как насчет этого?Мы можем использовать time.time (), чтобы получить текущее время (в формате UNIX).Если текущее время больше, чем last_time на 10 минут (60 секунд x 10), мы проверили погоду, мы вызываем функцию, чтобы получить погоду из API.

(непроверенный код, так как у меня нетlcddriver или ключ API)

import lcddriver
import time
import datetime
import requests, json 

display = lcddriver.lcd()

def get_weather():

    complete_url = "http://api.openweathermap.org/data/2.5/weather?q=CITY&APPID=****HIDE_API*****" 
    response = requests.get(complete_url)
    x = response.json() 

    if x["cod"] != "404": 
        return x
    else:
        return None

weather = None

try:
    last_update_time = 0
    while True:
        if last_update_time  + (60*10) > time.time():
            weather = get_weather()
            last_update_time = time.time()

        if weather:
            print("Writing to display")
            display.lcd_display_string("Temperatura zew:",1) 
            display.lcd_display_string(str(weather['temp']-273.15) + " C", 2) 
            time.sleep(10)  
            display.lcd_clear()                                   
            display.lcd_display_string("Cisnienie ", 1)
            display.lcd_display_string(str(weather['pressure']) + " hPa",2) 
            time.sleep(10) 
            display.lcd_clear()
            display.lcd_display_string("Wilgotnosc ", 1)
            display.lcd_display_string(str(weather['humidity']) + " %",2)
            time.sleep(10)                                    
            display.lcd_clear()                             
            time.sleep(1)                                    

except KeyboardInterrupt: # If there is a KeyboardInterrupt (when you press ctrl+c), exit the program and cleanup
    print("Cleaning up!")
    display.lcd_clear()
0 голосов
/ 31 января 2019
import threading, time

def fetch_data():
    threading.Timer(5.0, fetch_data).start()
    print(time.time())
    # Fetch data from api
    # Update LCD


fetch_data()
0 голосов
/ 31 января 2019

Если ваш код работает правильно, я не вижу ошибок.Вы можете поместить код в бесконечный цикл.

import time

x = 0
while True:
    print(x)
    x += 1
    time.sleep(1)

Приведенный выше пример кода будет печататься до тех пор, пока программа не будет остановлена ​​с интервалом 1 с:

0
1
2
3
.
.
.

вы можете сделать то же самоевместо этого используйте time.sleep(12*60).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...