2013-12-18 58 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