Python Web 服务开发者: 通过 SMTP 处理 SOAP
2008-09-30 13:01:38 来源:WEB开发网SOAP SMTP 客户机
SMTP SOAP 客户机需要侦听传入的邮件消息(它们代表应答),所以它看上去很象一个服务器实现。我们再次覆盖 smtpd.SMTPServer 来创建一个侦听器(在另一个端口上)以侦听应答(请参阅 清单 3)。服务器侦听器和客户机侦听器之间的一个很大的区别就是:我们在一个单独的线程中启动侦听器。这样我们就可以拥有两个线程,一个处理用户输入,另一个作为侦听器侦听并处理响应。
另一个区别就是侦听器包含一个“响应”字典,该字典将“In-Reply-To”标识映射为回调方法。使用这种方法,只要主输入线程向侦听器注册了每个请求,那么它愿意发出多少请求就可以发出多少。然后,主线程就可以继续快乐地工作,只要有响应进入,侦听器就会调用回调来处理它。
清单 3. 客户机侦听器代码class ClientServer(smtpd.SMTPServer):
#A simple server to receive our SOAP responses.
#The responses dictionary is a mapping from
#Message ID to a callback to handle the response.
responses = {}
#this is the method we must override in to handle SMTP messages
def process_message(self, peer, mailfrom, rcpttos, data):
#Parse the message into a email.Message instance
p = Parser.Parser()
m = p.parsestr(data)
#See if this is a reply that we were waiting for.
if m.has_key('In-Reply-To') and self.responses.has_key(m['In-Reply-To']):
mID = m['In-Reply-To']
#Invoke the response callback with the parsed SOAP.
self.responses[mID](mID,parse.ParsedSoap(m.get_payload(decode=1)))
del self.responses[mID]
else:
#In a product server, this would probably forward the message to another
#SMTP Server.
print "Unknown Email message"
print m
#method used to register that we are expecting a response from the server.
def expectResponse(self,mId,callback):
self.responses[str(mId)] = callback
更多精彩
赞助商链接