我想让一个函数永远运行,但我不想让它重复

问题描述 投票:0回答:1

我有一个请求流,我希望该流永远运行,但我不想重复。我希望该功能仅在流上有新信息时才更新,如果我尝试以一定的间隔运行它,则它会重复并且旧信息不断添加到容器中,并继续重复直到我关闭应用程序。

这是我的代码,对如何使容器仅更新新信息的任何修改,我将不胜感激。

    def processnotifications(self, dt):
        app = App.get_running_app()
        session = requests.Session()
        self.notif_stream = session.get("*********************************************************************" + app.displayname + "/.json", stream= True)
        print(self.notif_stream.json())
        if self.notif_stream.json() == None:
            return
        else:
            notifications = self.notif_stream.json()
            for key, value in notifications.items():
                self.notif = session.get("***************************************************" + app.displayname + "/" + key + "/" + "notification" + "/.json", stream = True)
                self.notificationslist.adapter.data.extend([self.notif.json()])

python python-requests kivy
1个回答
0
投票

我对这种解决方案不满意-我对数据做了很多假设,并决定跟踪在方法调用之间发生变化的项目。如果调用频率太高,这可能仍然很耗时并且对网站不是很友好。因此,更多的是作为救命稻草而不是答案...

我假设某些外部实体会定期调用此方法,并且对自上次调用以来发生了哪些事件更改感兴趣。这些被保留为随每次调用更新的对象上的一组键。

# todo: add to __init__
#     # previous notifications and a set of changed keys since
#     # the last call to processnotifications
#     self.notfications = {}
#     self.notification_changes = set()    

def processnotifications(self, dt):
    base_url = "***************************"
    app = App.get_running_app()
    session = requests.Session()

    # assume no notification changes
    self.notification_changes = set()

    # todo: do you need to keep the session? best to drop those references if not needed
    # todo: you read the full json so no need to stream

    # get current notifications, if any
    notif_stream = session.get(f"{app.displayname}/.json")
    notifications = notif_stream.json()
    print(notifications)
    if notifications == None:
        return False

    # assuming notifications change every time there are subnotifications we could
    # check here.
    if notifications = self.notifications:
        return False

    # remember current notifications        
    self.notifications = notifications
    data = self.notificationslist.adapter.data

    # get each subnotification and track which ones have changed
    changes = set()

    # note: value unused.... so no need to iterate .items()
    for key in notifications:
        notif = session.get(f"{base_url}{app.displayname}/{key}/notification/.json").json()
        if notif:
            for subkey, value in notif:
                # update self.notificationslist.adapter.datad iff we
                # got a notification with a different value
                if data.get(subkey, "") != value:
                    data[subkey] = value
                    changes.add(subkey)

    # record the changes we saw
    self.notification_changes = changes
    return bool(changes)
© www.soinside.com 2019 - 2024. All rights reserved.