我希望一个函数永远运行,但我不希望它重复



我有一个请求流,我希望该流永远运行,但我不希望它重复。我希望函数只在流上有新信息时更新,如果我尝试每隔一段时间运行它,它就会重复,旧信息会不断添加到容器中,并继续重复,直到我关闭应用程序。

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

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

我对这个解决方案不满意——我对数据做了很多假设,并决定跟踪在对方法的调用之间发生变化的项。如果经常调用,这可能仍然很耗时,并且对网站不太友好。所以,与其说是一个答案,不如说是一名司徒生。。。

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

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

相关内容

最新更新