繁体   English   中英

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

[英]Amazon SQS messages with arbitrary Python objects?

所以,我正在尝试使用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.

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM