【问题标题】:Get request - Python loop获取请求 - Python 循环
【发布时间】:2019-01-31 15:28:16
【问题描述】:

如何每 X 分钟从 openweather api 获取数据?我想使用 Raspberry Pi Zero W 在 16x2 LCD 上显示这些数据。

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()

【问题讨论】:

    标签: python api raspberry-pi openweathermap


    【解决方案1】:

    假设您的代码工作正常,因为我没有看到错误。您可以将代码置于无限循环中。

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

    上面的示例代码将一直打印到程序以 1 秒的间隔停止:

    0
    1
    2
    3
    .
    .
    .
    

    您也可以使用time.sleep(12*60)

    【讨论】:

      【解决方案2】:
      import threading, time
      
      def fetch_data():
          threading.Timer(5.0, fetch_data).start()
          print(time.time())
          # Fetch data from api
          # Update LCD
      
      
      fetch_data()
      

      【讨论】:

        【解决方案3】:

        这样的事情怎么样。我们可以使用 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()
        

        【讨论】:

        • 谢谢,但我有一个问题。当我启动脚本时,我看到错误:文件“test2.py”,第 24 行,在 if last_update_time + (60*10) > time.now(): AttributeError: 'module' object has no attribute 'now '
        • 啊!抱歉,应该是 time.time() 而不是 time.now()。我已经更新了我的示例
        猜你喜欢
        • 2018-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多