如何在函数类中保存临时数据?

2024-04-20 01:35:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要建立一个消息队列。我接收一条消息,对其运行转换并将其发送到输出队列。你知道吗

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部分,以及当前字典的“up next”。像这样的。你知道吗

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

然后,我可以包含一个if语句,当序列包含第0个_part时触发该语句,另一个按正确顺序发送每个部分序列。你知道吗

抱歉,这么久了。我的问题是,我如何在我的类example中存储这样一个字典,而不让它变得短暂,并且在运行新命令时消失?你知道吗


Tags: inself消息队列def序列msgcontent