所以,我正在尝试使用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.
我想我的问题的答案可能在那一段,但我无法理解。任何人都可以提供具体的代码示例来说明他们在谈论什么吗?
答案 0 :(得分:5)
对于任意Python对象,答案是将对象序列化为字符串,使用SQS将该字符串发送到另一个EC2实例,并将字符串反序列化为同一类的实例。
例如,您可以使用带有base64编码的JSON将对象序列化为字符串,这将是您的消息正文。