Python 自动更新功能

Python auto-update function

我正在为一个项目编写这段代码,我有这个 class 可以从 OWM 解析天气。 我的这部分代码如下所示:

class Meteo():
    def __init__(self):
        self.API = pyowm.OWM('My API Key', config_module=None,
                             language='it', subscription_type=None)
        self.location = self.API.weather_at_place('Rome,IT')
        self.weatherdata = self.location.get_weather()
        self.weather = str(self.weatherdata.get_detailed_status())

    def Temperature(self):
        self.tempvalue = self.weatherdata.get_temperature('celsius')
        temperature = str(self.tempvalue.get('temp'))
        return temperature

当然,问题是,运行 下午 2 点的程序是 20°C,到凌晨 2 点它仍然会显示相同的温度,因为(显然)它保持了它的温度在启动时解析。 我在网上搜索了自动更新 python 功能,但我没有找到解释我的情况的问题。 如果有人能回答或给我指出解释的地方,我将不胜感激。 谢谢

我只想更新天气数据,然后 return 温度:

def update_weather(self):
    self.weatherdata = self.location.get_weather()
    self.weather = str(self.weatherdata.get_detailed_status())

def Temperature(self):
    update_weather()
    self.tempvalue = self.weatherdata.get_temperature('celsius')
    temperature = str(self.tempvalue.get('temp'))
    return temperature

您需要的是一个 属性,它具有带时间戳的缓存值,以便在该值过期时发出请求以获取当前值。是这样的: 它可以做成装饰器,但需要更长的时间:

class Meteo():
    def __init__(self):
        self.last_update = 0

    def Temperature(self):

        if (time.time() - self.last_update) > 60: # cache the value for 60 seconds
            self.API = pyowm.OWM('My API Key', config_module=None,
                                 language='it', subscription_type=None)
            self.location = self.API.weather_at_place('Rome,IT')
            self.weatherdata = self.location.get_weather()
            self.weather = str(self.weatherdata.get_detailed_status())
            self.last_update = time.time()

        self.tempvalue = self.weatherdata.get_temperature('celsius')
        temperature = str(self.tempvalue.get('temp'))
        return temperature

无论调用多少次Temperature,它最多每60秒发出一次请求。

总的来说,没有什么神奇的事情发生。如果您需要当前数据,则需要获取它。

您可以选择多种条件来触发 'data update',例如,如果您正在以某种形式或按计划处理数据。

如果在您的用例中每小时获取当前温度就足够了,听起来某种形式的 cron 作业可以解决您的问题。 cron 作业的全部意义在于按预设计划执行任务。签出 Wikipedia.

也许 Aaron_ab (How do I get a Cron like scheduler in Python?) 中的 link 最适合您的情况。 或者看看 Celery Beat.

如果您不需要您的应用程序 运行 整个时间,最好在您的 OS 上使用 cron 并让它在需要时执行您的应用程序。