首页 > 解决方案 > 如何在函数类中保存临时数据?

问题描述

我需要创建一个消息队列。我收到一条消息,对其运行转换并将其发送到输出队列。

import queue
import json
import re

Class example:
    def __init__(self):
        self.outputZero  = queue.Queue()
        self.outputOne   = queue.Queue()

   def transform(self, msg):
        messageDict = json.loads(msg)
        keys = [i for i in messageDict.keys()]

        for i in keys:             
            # reverse strings that include "bonkers
            if re.search("bonkers", str(messageDict[i])):
                messageDict[i] = messageDict[i][::-1]

        return messageDict

    def dispatch(self, msg):
        if "_special" in keys:
            self.outputZero.put(messageDict)
        elif "hash" in keys:
            self.outputOne.put(messageDict)

    def enqueue(self, msg):
       #transform the message
       cleanmsg = self.transform(msg)
       #dispatch the message
       self.dispatch(cleanmsg)

问题是我需要处理序列。我需要能够处理包含两部分的消息,一个_sequence是序列的 id,另一个是序列_part中的消息编号,从零开始。

我需要使用序列中的第一条消息来确定所有其余消息的队列,然后以正确的顺序将它们发送到根据第一条消息确定的任何队列。

这是一些消息的示例。

input00 = '{"thefield": "themessage", "_privatefield" : "content", "_sequence" : "aeiou", "_part":"3"}' 
input01 = '{"thefield": "onemore", "_privatefield" : "content", "_sequence" : "aeiou", "_part":"1"}'
input02 = '{"thefield": "yetanother", "_privatefield" : "content", "_sequence" : "aeiou", "_part":"2"}' 
input03 = '{"thefield": "lastone", "_privatefield" : "content", "_sequence" : "aeiou", "_part":"0"}'

我的解决方案是存储一个字典,其中包含每个序列 ID 以及是否包含第 0 部分以及“下一个”的当前字典。像这样的东西。

sequenceDict[input["_sequence"]]["_part"] = input00

然后,我可以包含一个 if 语句,该语句在包含第 0 个序列时触发_part,另一个以正确的顺序发送每个系列的部分。

对不起,这已经很久了。我的问题是,我怎样才能将这样的字典存储在我的班级中example,而不会在运行新命令时它是短暂的并且只是消失?

标签: pythonpython-3.xdictionaryqueuemessage-queue

解决方案


推荐阅读