带有任意Python对象的Amazon SQS消息?

 绿茶2602921445 发布于 2023-02-09 13:34

所以,我正在尝试使用SQS在两个EC2实例之间传递Python对象.这是我失败的尝试:

import boto.sqs
from boto.sqs.message import Message

class UserInput(Message):
    def set_email(self, email):
        self.email = email
    def set_data(self, data):
        self.data = data
    def get_email(self):
        return self.email
    def get_data(self):
        return self.data

conn = boto.sqs.connect_to_region('us-west-2')
q = conn.create_queue('user_input_queue')
q.set_message_class(UserInput)
m = UserInput()
m.set_email('something@something.com')
m.set_data({'foo': 'bar'})
q.write(m)

它会返回一条错误消息The request must contain the parameter MessageBody.实际上,该教程告诉我们m.set_body('something')在将消息写入队列之前要做的事情.但是这里我没有传递字符串,我想传递一个UserInput类的实例.那么,MessageBody应该是什么?我已经阅读了文档并且他们说了

The constructor for the Message class must accept a keyword parameter “body” which represents the content or body of the message. The format of this parameter will depend on the behavior of the particular Message subclass. For example, if the Message subclass provides dictionary-like behavior to the user the body passed to the constructor should be a dict-like object that can be used to populate the initial state of the message.

我想我的问题的答案可能在那一段,但我无法理解.任何人都可以提供具体的代码示例来说明他们在谈论什么吗?

1 个回答
  • 对于任意Python对象,答案是将对象序列化为字符串,使用SQS将该字符串发送到另一个EC2实例,并将字符串反序列化回同一个类的实例.

    例如,您可以使用带有base64编码的JSON将对象序列化为字符串,这将是您的消息正文.

    2023-02-09 13:36 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有