2011-05-17 95 views
1

我想用python的Template對象來創建html電子郵件。然而,當應用程序試圖發送我的錯誤的電子郵件:python編碼/解碼問題

File "/base/data/home/apps/hanksandbox/1.350486862928605153/main.py", line 573, in post 
html = messages.email_document_html(document) 
File "/base/data/home/apps/hanksandbox/1.350486862928605153/messages.py", line 109, in email_document_html 
description = document.get_description() 
File "/base/python_runtime/python_dist/lib/python2.5/string.py", line 170, in substitute 
return self.pattern.sub(convert, self.template) 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 763: ordinal not in range(128) 

代碼中的錯誤指的模樣:

def email_document_html(document): 
email_document = Template(""" 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
    ${stylesheet} 
</head> 
<html> 
<body> 
<h1 id="mainhead">Essays</h1> 
<div class="document"> 
<span class="info">At ${date} ${author} published:</span><br/><hr/> 
<a href="${domain}/${author}/document/${filename}/" target="_blank"><h1 class="title">${title}</h1></a> 
<p class="description">${description}</p> 
</div> 
</body> 
</html> 
""") 
return email_document.substitute(
           stylesheet=style, 
           date=str(document.date), 
           author=document.author.username, 
           domain=domainstring, 
           filename=document.filename, 
           title=document.title, 
           description = document.get_description() 
           ) 

我的IDE使用UTF-8作爲其字符集。我已經嘗試將# coding: utf-8添加到我的文件中。我試過在'document.get_description()'之後的各個地方添加.encode("utf-8").decode("utf-8")。但我正在抓秸稈。

有什麼建議嗎?

回答

2

將一個u模板字符串之前指定它旨在成爲一個unicode字符串。 Python除非另有說明,否則將其解釋爲ASCII。

email_document = Template(u""" 
... 
+0

謝謝!我無法相信我在一封小字母「u」上花費了數小時的時間。 – Hank 2011-05-18 00:08:58