本文整理汇总了Python中mimetools.decode函数的典型用法代码示例。如果您正苦于以下问题:Python decode函数的具体用法?Python decode怎么用?Python decode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了decode函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: _make_tempfile
def _make_tempfile(self):
transfer_encoding = self.headers.get('content-transfer-encoding',
'').lower()
tf = NamedTemporaryFile()
start_pos = self._pos + self._headers_length + 2
file_length = (self._endpos - 2) - start_pos
bytes_read = 0
self._data.seek(start_pos)
while bytes_read < file_length:
remaining_bytes = (self._endpos - 2) - self._data.tell()
chunk_size = min(8196, remaining_bytes)
tf.write(self._data.read(chunk_size))
bytes_read += chunk_size
tf.seek(0)
if transfer_encoding not in ('', '7bit', '8bit', 'binary'):
decoded_tf = NamedTemporaryFile()
mimetools.decode(tf, decoded_tf, transfer_encoding)
try:
return codecs.getreader(self.charset)(decoded_tf)
except (TypeError, LookupError):
return decoded_tf
else:
try:
return codecs.getreader(self.charset)(tf)
except (TypeError, LookupError):
return tf
开发者ID:countach74,项目名称:gimme,代码行数:30,代码来源:multipart.py
示例2: __init__
def __init__(self, ct, f, next=None, uribase='thismessage:/',
seekable=0, **kw):
# Get the boundary. It's too bad I have to write this myself,
# but no way am I going to import cgi for 10 lines of code!
for param in ct.split(';'):
a = param.strip()
if a.startswith('boundary='):
if a[9] in [ '"', "'" ]:
boundary = a[10:-1]
else:
boundary = a[9:]
break
else:
raise ValueError('boundary parameter not found')
self.id_dict, self.loc_dict, self.parts = {}, {}, []
self.next = next
self.base = uribase
mf = multifile.MultiFile(f, seekable)
mf.push(boundary)
while next(mf):
head = mimetools.Message(mf)
body = StringIO.StringIO()
mimetools.decode(mf, body, head.getencoding())
body.seek(0)
part = (head, body)
self.parts.append(part)
key = head.get('content-id')
if key:
if key[0] == '<' and key[-1] == '>': key = key[1:-1]
self.id_dict[key] = part
key = head.get('content-location')
if key: self.loc_dict[key] = part
mf.pop()
开发者ID:istobran,项目名称:python-ZSI-py3,代码行数:35,代码来源:resolvers.py
示例3: decode
def decode(self):
if self.encoding in ['7bit', '8bit']:
return self.body
self.rewindbody()
out = StringIO()
mimetools.decode(StringIO(self.body), out, self.encoding)
return out.getvalue() # XXX look if there an error occurs
开发者ID:MinasAbrahamyan,项目名称:bobomail,代码行数:7,代码来源:Message.py
示例4: msgRetrieve
def msgRetrieve(self, message, part="RFC822", encoding=None):
"""Retrieve a full message or a message part for this UID
You can get a message part if you specify the part id
by default it returns the whole RFC822 part of it
Although theoretically it could fetch multiple parts, imaplib
massacrates the result so it's difficult to parse.
Specify encoding type to get the data back decoded
"""
# Convert part number to IMAP-style "BODY[part]"
if '0' < part[0] <= '9':
part = "BODY[%s]" % part
result = self.imap.uid("FETCH", message, "(" + part + ")")
result = self._checkStatus(result)
if not result[0]:
return None
data = result[0][1] # imaplib split the returned literal
# see if we need to decode it.
if encoding in ('base64', 'quoted-printable', 'uuencode'):
output = cStringIO.StringIO()
input = cStringIO.StringIO(data)
mimetools.decode(input, output, encoding)
input.close()
data = output.getvalue()
output.close()
return data
开发者ID:laurb9,项目名称:python-imap4rev1,代码行数:32,代码来源:imap4rev1.py
示例5: decode_content
def decode_content(message):
"""Decode the content of a message. This method do not checks if the message is
multipart or if the message mime type is plain text or html.
Parameters
----------
message: email.message.Message
Message to decode.
Returns
-------
content: str
Decoded content of the message
Raises
------
TypeError
If the parameter is not an instance of :class:`email.message.Message`.
"""
if not isinstance(message, email.message.Message):
raise TypeError("Expected a message object.")
encoding = message['Content-Transfer-Encoding']
if encoding and encoding.strip() == 'quoted-printable':
result = message.get_payload()
stream = cStringIO.StringIO(result)
output = cStringIO.StringIO()
mimetools.decode(stream, output, 'quoted-printable')
return output.getvalue()
return message.get_payload(decode=True)
开发者ID:tmpethick,项目名称:anki-onenote-importer,代码行数:29,代码来源:text.py
示例6: process_mime_body
def process_mime_body(current, file, submsg):
data = StringIO.StringIO()
try:
mimetools.decode(file, data, submsg.getencoding())
current['description'] = data.getvalue()
except:
return
开发者ID:3rdEyes-1,项目名称:bugzilla,代码行数:7,代码来源:jb2bz.py
示例7: getbodytext
def getbodytext(self, decode = 1):
self.fp.seek(self.startofbody)
encoding = self.getencoding()
if not decode or encoding in ('7bit', '8bit', 'binary'):
return self.fp.read()
from StringIO import StringIO
output = StringIO()
mimetools.decode(self.fp, output, encoding)
return output.getvalue()
开发者ID:asottile,项目名称:ancient-pythons,代码行数:9,代码来源:mhlib.py
示例8: Opaque
def Opaque(uri, tc, ps, **keywords):
'''Resolve a URI and return its content as a string.
'''
source = urllib.request.urlopen(uri, **keywords)
enc = source.info().getencoding()
if enc in ['7bit', '8bit', 'binary']: return source.read()
data = StringIO.StringIO()
mimetools.decode(source, data, enc)
return data.getvalue()
开发者ID:istobran,项目名称:python-ZSI-py3,代码行数:10,代码来源:resolvers.py
示例9: test_decodeencode
def test_decodeencode(self):
start = string.ascii_letters + "=" + string.digits + "\n"
for enc in ["7bit", "8bit", "base64", "quoted-printable", "uuencode", "x-uuencode", "uue", "x-uue"]:
i = StringIO.StringIO(start)
o = StringIO.StringIO()
mimetools.encode(i, o, enc)
i = StringIO.StringIO(o.getvalue())
o = StringIO.StringIO()
mimetools.decode(i, o, enc)
self.assertEqual(o.getvalue(), start)
开发者ID:Jarga,项目名称:IBM-Innovate-2012,代码行数:10,代码来源:test_mimetools.py
示例10: Opaque
def Opaque(uri, tc, ps, **keywords):
"""Resolve a URI and return its content as a string.
"""
source = urllib.urlopen(uri, **keywords)
enc = source.info().getencoding()
if enc in ["7bit", "8bit", "binary"]:
return source.read()
data = StringIO.StringIO()
mimetools.decode(source, data, enc)
return data.getvalue()
开发者ID:ndawe,项目名称:pyAMI,代码行数:11,代码来源:resolvers.py
示例11: test_decodeencode
def test_decodeencode(self):
start = string.ascii_letters + "=" + string.digits + "\n"
for enc in ['7bit','8bit','base64','quoted-printable',
'uuencode', 'x-uuencode', 'uue', 'x-uue']:
i = StringIO.StringIO(start)
o = StringIO.StringIO()
mimetools.encode(i, o, enc)
i = StringIO.StringIO(o.getvalue())
o = StringIO.StringIO()
mimetools.decode(i, o, enc)
self.assertEqual(o.getvalue(), start)
开发者ID:B-Rich,项目名称:breve,代码行数:11,代码来源:test_mimetools.py
示例12: XML
def XML(uri, tc, ps, **keywords):
'''Resolve a URI and return its content as an XML DOM.
'''
source = urllib.request.urlopen(uri, **keywords)
enc = source.info().getencoding()
if enc in ['7bit', '8bit', 'binary']:
data = source
else:
data = StringIO.StringIO()
mimetools.decode(source, data, enc)
data.seek(0)
dom = ps.readerclass().fromStream(data)
return _child_elements(dom)[0]
开发者ID:istobran,项目名称:python-ZSI-py3,代码行数:13,代码来源:resolvers.py
示例13: getbodytext
def getbodytext(self, decode = 1):
"""Return the message's body text as string. This undoes a
Content-Transfer-Encoding, but does not interpret other MIME
features (e.g. multipart messages). To suppress decoding,
pass 0 as an argument."""
self.fp.seek(self.startofbody)
encoding = self.getencoding()
if not decode or encoding in ('', '7bit', '8bit', 'binary'):
return self.fp.read()
from StringIO import StringIO
output = StringIO()
mimetools.decode(self.fp, output, encoding)
return output.getvalue()
开发者ID:B-Rich,项目名称:breve,代码行数:13,代码来源:mhlib.py
示例14: extract_mime_part_matching
def extract_mime_part_matching(stream, mimetype):
mfile = multifile.MultiFile(stream)
mfile.push("_BOUNDRY_02468_STRING_13579_XXXXXXX")
while 1:
submsg = mimetools.Message(mfile)
data = StringIO.StringIO()
mimetools.decode(mfile, data, submsg.getencoding())
if (not mfile.next()) or submsg.gettype() == mimetype : break
mfile.pop()
return data.getvalue()
开发者ID:Dealermade,项目名称:canonCameraControl,代码行数:14,代码来源:accessCamera.py
示例15: mimedecode
def mimedecode(self, msg=None, id=""):
if not msg:
self.rewind()
msg = mimetools.Message(self, 0)
type = msg.gettype()
if (len(id) > 5):
# Emergency abort!
return [["(diagnostic)", "text/plain", \
"Attachments too deeply nested --- aborting (probably hit the Multifile bug)", \
id+"A"]]
disposition = msg.getheader("Content-Disposition")
disposition = sqmail.utils.parse_mimeheader(disposition)
name = msg.getparam("name")
index = 65
if not name:
name = sqmail.utils.get_mime_param(disposition, "filename")
if not name:
name = "<unnamed>"
if (type[:10] == "multipart/"):
multi = multifile.MultiFile(msg.fp, 0)
multi.push(msg.getparam("boundary"))
l = []
while multi.next():
l.append(self.mimedecode(mimetools.Message(multi, 0), id+chr(index))[0])
index = index + 1
if (index > 65+32):
# Emergency abort!
raise MIMEDecodeAbortException
multi.pop()
return [[name, type, l, ""]]
else:
encoding = msg.getencoding()
if (encoding != "7bit") and (encoding != "8bit"):
data = cStringIO.StringIO()
mimetools.decode(msg.fp, data, msg.getencoding())
return [[name, type, data.getvalue(), id]]
else:
return [[name, type, string.join(msg.fp.readlines(), ""), id]]
开发者ID:davidgiven,项目名称:sqmail,代码行数:39,代码来源:message.py
示例16: maybe_add_attachment
def maybe_add_attachment(current, file, submsg):
"""Adds the attachment to the current record"""
cd = submsg["Content-Disposition"]
m = re.search(r'filename="([^"]+)"', cd)
if m == None:
return
attachment_filename = m.group(1)
if (submsg.gettype() == 'application/octet-stream'):
# try get a more specific content-type for this attachment
type, encoding = mimetypes.guess_type(m.group(1))
if type == None:
type = submsg.gettype()
else:
type = submsg.gettype()
try:
data = StringIO.StringIO()
mimetools.decode(file, data, submsg.getencoding())
except:
return
current['attachments'].append( ( attachment_filename, type, data.getvalue() ) )
开发者ID:3rdEyes-1,项目名称:bugzilla,代码行数:22,代码来源:jb2bz.py
示例17: _extractMimeParts
def _extractMimeParts(stream):
msg = mimetools.Message(stream)
msgtype = msg.gettype()
params = msg.getplist()
files = []
raw_data = cStringIO.StringIO()
if msgtype[:10] == "multipart/":
f = multifile.MultiFile(stream)
f.push(msg.getparam("boundary"))
while f.next():
submsg = mimetools.Message(f)
filename = submsg.getheader(MIME_FILE_HEADER)
content_hash = submsg.getheader(MIME_HASH_HEADER)
try:
raw_data = cStringIO.StringIO()
mimetools.decode(f, raw_data, submsg.getencoding())
except ValueError:
continue
files.append((filename, content_hash, raw_data.getvalue()))
f.pop()
return files
开发者ID:fajoy,项目名称:typhoonae,代码行数:23,代码来源:service.py
示例18:
from test_support import TestFailed
import mimetools
import string,StringIO
start = string.ascii_letters + "=" + string.digits + "\n"
for enc in ['7bit','8bit','base64','quoted-printable']:
print enc,
i = StringIO.StringIO(start)
o = StringIO.StringIO()
mimetools.encode(i,o,enc)
i = StringIO.StringIO(o.getvalue())
o = StringIO.StringIO()
mimetools.decode(i,o,enc)
if o.getvalue()==start:
print "PASS"
else:
print "FAIL"
print o.getvalue()
开发者ID:denis-vilyuzhanin,项目名称:OpenModelSphereMirror,代码行数:18,代码来源:test_mimetools.py
示例19: file
while mfile.next():
submsg = mimetools.Message(mfile)
if submsg.gettype() != "image/jpeg":
continue
now = time.localtime(time.time())
fileNum = 1
while True:
format = "%%Y-%%m-%%d-%%H:%%M-%d.jpg" % fileNum
jpegFileName = time.strftime(format,
# Backward compatible
now)
if os.path.exists(jpegFileName) == False:
break
fileNum = fileNum + 1
jpegFile = file(jpegFileName, "w")
mimetools.decode(mfile, jpegFile, submsg.getencoding())
jpegFile.close()
mfile.pop()
# We have now created the file jpegFileName, time to add it to the
# index.html file
html = file("index.html", "r")
newhtml = file("index-new.html", "w")
asctime = time.asctime(now)
while True:
line = html.readline()
if len(line) == 0:
break
if line[0:13] == "<!-- MARK -->":
newhtml.write("<!-- MARK --><img src=\"%s\"><br>\n" % jpegFileName)
newhtml.write("<a href=\"%s\">%s</a><br>\n" % (jpegFileName, asctime))
开发者ID:von,项目名称:scripts,代码行数:31,代码来源:parse_photo.py
示例20: open
f = open("indian.txt", 'rb')
print "Writing initial indian.wav from email text file..."
input = ''.join([x.rstrip("\n") for x in f])
#input = [[x for x in reversed(input[i:i+8])] for i in range(0, len(input), 8)]
#input = sum(input, [])
#input = ''.join(input)
inputFile = open("indian.in", 'wb')
inputFile.write(input)
inputFile.close()
out = open("indian.wav", 'wb')
mt.decode(open("indian.in", 'rb'), out, 'base64')
print "Byteswapping the audio of indian.wav...."
a = array.array('i')
w = wave.open("indian.wav", 'rb')
wout = wave.open("final_indian.wav", 'wb')
a.fromstring(w.readframes(w.getnframes()))
a.byteswap()
wout.setparams(w.getparams())
wout.writeframes(a.tostring())
w.close()
wout.close()
print "Wrote byteswapped file to final_indian.wav"
开发者ID:cemulate,项目名称:python-challenge,代码行数:31,代码来源:p19.py
注:本文中的mimetools.decode函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论