【问题标题】:Amazon SQS messages with arbitrary Python objects?带有任意 Python 对象的 Amazon SQS 消息?
【发布时间】:2014-01-07 01:02:10
【问题描述】:

所以,我正在尝试使用 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。事实上,tutorial 告诉我们在将消息写入队列之前执行m.set_body('something')。但是在这里我没有传递字符串,我想传递我的 UserInput 类的实例。那么,MessageBody 应该是什么?我读过docs,他们这么说

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.

我想我的问题的答案可能在那段中,但我无法理解它。谁能提供一个具体的代码示例来说明他们在说什么?

【问题讨论】:

    标签: python amazon-web-services amazon-ec2 boto amazon-sqs


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-09-24
      • 1970-01-01
      • 2014-11-10
      • 2016-03-05
      • 2015-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-09
      相关资源
      最近更新 更多