2013-12-18 23 views
4

所以,我试图使用SQS在两个EC2实例之间传递一个Python对象。这是我的失败尝试:具有任意Python对象的Amazon SQS消息?

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('[email protected]') 
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.

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

回答

5

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

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

+0

这样做。谢谢! – Parzival