2011-05-12 123 views
0

我對Google App Engine(和python)的合理新手我正在實現一個系統,該系統將基本解析傳入的電子郵件並將詳細信息存儲在Data Store中。現在我確實有工作,但我覺得現在應該有更好的方式來做到這一點。使用Google App Engine從電子郵件中收集數據

基本上,進來到系統中的電子郵件總是看起來像下面這樣:

Order Details: Random Batch Name here 

Order Status: 74 of 131 Shipped In Total 

Message ID: 123456 

Message Date: 21/04/2011 16:13:00 

Mobile Number:

Message: message would be here 

我使用解析它看起來像這樣的代碼:

class LogSenderHandler(InboundMailHandler): 
    def receive(self, message): 

     # Get the body text from the e-mail 
     plaintext_bodies = message.bodies('text/plain') 
     for content_type, body in plaintext_bodies: 
      body_text = body.decode().split('\n') 

      # Loop through each line in the e-mail and discard a line if it is blank 
      for line in body_text: 
       if line != "": 

        # I'm sure there's a better way of doing this, just don't know how right now! 
        # Split the current line based on the ": " value and only let it be done once 
        splitline = line.split(': ', 1) 

        # Check to see which line we now have the details for and place value into the correct variable 
        if splitline[0] == "Order Details": 
         batch = splitline[1] 
        if splitline[0] == "Message ID": 
         messageID = splitline[1] 
        if splitline[0] == "Message Date": 
         messageDate = splitline[1] 
        if splitline[0] == "Mobile Number": 
         mobileNumber = splitline[1] 
        if splitline[0] == "Message": 
         theMessage = splitline[1] 


     newNumber = SMSNumber(status = "Waiting", 
           batch = common.slugify(batch), 
           messageID = messageID, 
           messageDate = messageDate, 
           sentMessage = theMessage) 

     newNumber._key_name = mobileNumber 
     newNumber.put() 

有處理這個問題的更好方法是?如果有人有任何意見,我們將非常感激! :)

問候

+0

「更好」是什麼意思? – geoffspear 2011-05-12 13:22:52

+0

確實效率更高。 – vultuk 2011-05-12 13:27:27

+0

http://docs.python.org/library/email.parser.html也許這一個? 'import email >>> msg = email.message_from_string(myString)' – lucemia 2011-05-12 20:10:34

回答

0

一個整齊的方法是通過文件,分割對結腸的線進行迭代,並添加線到Map。然後,從地圖中讀出相關條目並將它們傳遞給構造函數 - 指定一個默認值,以防它不存在。

相關問題