简体   繁体   English

持久列表Python实现

[英]Persistent List Python Implementation

I have class that sends logs to an exposed API. 我有将日志发送到公开的API的类。 Now what I want to happen is to save/persists failed logs in a list so that it can be resent to the server again. 现在,我要执行的操作是将失败的日志保存/持久保存在列表中,以便可以再次将其重新发送到服务器。

This is what I have so far. 到目前为止,这就是我所拥有的。 You may notice that I have declared a class variable, and I have read that this is not really advisable. 您可能会注意到,我已经声明了一个类变量,并且我读到这并不是真正可取的。

My concern is, is there a better way to persist lists or queues? 我担心的是,是否有更好的方法来保留列表或队列?

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"})

Since the only variable LogManager stores is a persistent one, there doesn't seem to be any need to re-instantiate the class each time. 由于LogManager唯一存储的变量是持久变量,因此似乎不需要每次都重新实例化该类。 I would probably move the logs = LogManager() line outside of the while-loop and change list_queue to an instance variable, self.list_queue that is created in the class' __init__ method. 我可能logs = LogManager()行移到while循环之外,并将list_queue更改为在类的__init__方法中创建的实例变量self.list_queue This way you'll have one LogManager with one queue that just calls its run method each loop. 这样,您将拥有一个LogManager和一个队列,每个队列仅run每个循环中调用其run方法。

That said, if you're keeping it inside the loop because your class will have further functionality that requires a new instance each loop, then using a class variable to track a list between instances is exactly what class variables are for. 就是说,如果您将其保留在循环中是因为您的类将具有进一步的功能,每个循环都需要一个新实例,那么使用类变量来跟踪实例之间的列表正是该类变量的用途。 They're not inadvisable at all; 它们一点也不不可取。 the example given in the documentation you link to is bad because they're using a class variable for data that should be instance-specific. 您链接到的文档中给出的示例很糟糕,因为它们使用类变量存储应特定于实例的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM