持久列表Python实现
我有一个将日志发送到公开API的类。现在,我想做的是将失败日志保存/持久化到列表中,以便再次将其重新发送到服务器 这就是我目前所拥有的。 您可能会注意到,我已经声明了一个类变量,我知道这实际上是不可取的 我关心的是,有没有更好的方法来持久化列表或队列持久列表Python实现,python,list,python-3.x,queue,Python,List,Python 3.x,Queue,我有一个将日志发送到公开API的类。现在,我想做的是将失败日志保存/持久化到列表中,以便再次将其重新发送到服务器 这就是我目前所拥有的。 您可能会注意到,我已经声明了一个类变量,我知道这实际上是不可取的 我关心的是,有没有更好的方法来持久化列表或队列 from collections import * import time import threading import requests import json URL_POST = "http:/some/url/here" class
from collections import *
import time
import threading
import requests
import json
URL_POST = "http:/some/url/here"
class LogManager:
listQueue = deque()
def post(self, log):
headers = {"Content-type": "application/json",
"Accept": "text/plain", "User-Agent": "Test user agent"}
resp = requests.post(URL_POST, data=json.dumps(log), headers=headers)
return resp.status_code
def send_log(self, log):
try:
print ("Sending log to backend")
self.post(log)
except: # sending to server fails for some reason
print ("Sending logs to server fail, appending to Queue")
LogManager.listQueue.append(log)
def resend_log(self, log):
print ("checking if deque has values")
if LogManager.listQueue:
logToPost = LogManager.listQueue.popleft()
try:
self.post(logToPost)
print ("resending failed logs")
except: #for some reason it fails again
LogManager.listQueue.appendleft(logToPost)
print ("appending log back to deque")
def run(self,log):
t1 = threading.Thread(target=self.send_log, args=(log,))
t2 = threading.Thread(target=self.resend_log,args=(log,))
t1.start()
time.sleep(2)
t2.start()
t1.join()
t2.join()
if __name__ == "__main__":
while True:
logs = LogManager()
logs.run({"some log": "test logs"})
由于LogManager存储的唯一变量是持久变量,因此似乎不需要每次都重新实例化该类。我可能会将logs=LogManager行移到while循环之外,并将list\u queue更改为实例变量self.list\u queue,该变量是在类'\uuuuu init\uu'方法中创建的。这样,您将有一个日志管理器和一个队列,每个循环只调用其run方法 也就是说,如果您将其保留在循环中,因为您的类将具有进一步的功能,每个循环都需要一个新实例,那么使用类变量来跟踪实例之间的列表正是类变量的用途。他们一点也不是不可取的;您链接到的文档中给出的示例是错误的,因为他们使用了一个类变量来表示应该是特定于实例的数据