[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

caveat: punts for type application/octet-stream even if it has
safe filename extension such as .html; caveat: image/audio/video
could be opened with the book's playfile.py; could also do that
if text viewer fails: would start notepad on Windows via startfile;
webbrowser may handle most cases here too, but specific is better;
"""


def textPartEncoding(fullfilename):
"""
3.0: map a text part filename back to charset param in content-type
header of part's Message, so we can pass this on to the PyEdit
constructor for proper text display; we could return the charset
along with content-type from mailtools for text parts, but fewer
changes are needed if this is handled as a special case here;


part content is saved in binary mode files by mailtools to avoid
encoding issues, but here the original part Message is not directly
available; we need this mapping step to extract a Unicode encoding
name if present; 4E's PyEdit now allows an explicit encoding name for
file opens, and resolves encoding on saves; see Chapter 11 for PyEdit
policies: it may ask user for an encoding if charset absent or fails;
caveat: move to mailtools.mailParser to reuse for in PyMailCGI?
"""
partname = os.path.basename(fullfilename)
for (filename, contype, part) in self.walkNamedParts(self.origMessage):
if filename == partname:
return part.get_content_charset() # None if not in header
assert False, 'Text part not found' # should never happen


for (contype, fullfilename) in partfiles:
maintype = contype.split('/')[0] # left side
extension = os.path.splitext(fullfilename)[1] # not [-4:]
basename = os.path.basename(fullfilename) # strip dir


HTML and XML text, web pages, some media


if contype in ['text/html', 'text/xml']:
browserOpened = False
if self.askOpen(appname, 'Open "%s" in browser?' % basename):
try:
webbrowser.open_new('file://' + fullfilename)
browserOpened = True
except:
showerror(appname, 'Browser failed: trying editor')
if not browserOpened or not self.skipTextOnHtmlPart:
try:


try PyEdit to see encoding name and effect


encoding = textPartEncoding(fullfilename)
textEditor.TextEditorMainPopup(parent=self,
winTitle=' - %s email part' % (encoding or '?'),
loadFirst=fullfilename, loadEncode=encoding)
except:
showerror(appname, 'Error opening text viewer')


text/plain, text/x-python, etc.; 4E: encoding, may fail


1090 | Chapter 14: The PyMailGUI Client

Free download pdf