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 部分以及“下一个”的当前字典。像这样的东西。
sequenceDict[input["_sequence"]]["_part"] = input00
然后,我可以包含一个 if 语句,该语句在包含第 0 个序列时触发_part
,另一个以正确的顺序发送每个系列的部分。
对不起,这已经很久了。我的问题是,我怎样才能将这样的字典存储在我的班级中example
,而不会在运行新命令时它是短暂的并且只是消失?
解决方案
推荐阅读
- java - 如何更新不显示片段
- c# - 带有特殊字符的 WOPI 文件名未在在线编辑器中打开文件
- php - SQl 根据 ID 匹配从两个表更新到另一个表
- vue.js - 我正在尝试在 Vue.Js 中构建一个 CRUD 应用程序我无法插入用户
- linux - npm install 在 docker 内部的私有存储库中未运行准备钩子
- xaml - Windows UI 库 - 如何调用动态添加的 NavigationView.MenuItems
- javascript - React map 函数:如何一次输出所有嵌套数组的内容?
- android - 在 Android 模拟器上运行 react-native 项目不起作用
- python - 使用python从pdf转换为文本文件后缺少空格
- windows-10 - SNMPv3 - 将自定义 MIB 文件转换为 python MIB 文件