Use cStringIO where available.

This commit is contained in:
Raymond Hettinger 2004-12-31 19:15:26 +00:00
parent 54266fce8d
commit a617271dbd
8 changed files with 55 additions and 19 deletions

View file

@ -410,7 +410,11 @@ class URLopener:
def open_local_file(self, url):
"""Use local file."""
import mimetypes, mimetools, email.Utils, StringIO
import mimetypes, mimetools, email.Utils
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
host, file = splithost(url)
localname = url2pathname(file)
try:
@ -420,7 +424,7 @@ class URLopener:
size = stats.st_size
modified = email.Utils.formatdate(stats.st_mtime, usegmt=True)
mtype = mimetypes.guess_type(url)[0]
headers = mimetools.Message(StringIO.StringIO(
headers = mimetools.Message(StringIO(
'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
(mtype or 'text/plain', size, modified)))
if not host:
@ -441,7 +445,11 @@ class URLopener:
def open_ftp(self, url):
"""Use FTP protocol."""
import mimetypes, mimetools, StringIO
import mimetypes, mimetools
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
host, path = splithost(url)
if not host: raise IOError, ('ftp error', 'no host given')
host, port = splitport(host)
@ -490,7 +498,7 @@ class URLopener:
headers += "Content-Type: %s\n" % mtype
if retrlen is not None and retrlen >= 0:
headers += "Content-Length: %d\n" % retrlen
headers = mimetools.Message(StringIO.StringIO(headers))
headers = mimetools.Message(StringIO(headers))
return addinfourl(fp, headers, "ftp:" + url)
except ftperrors(), msg:
raise IOError, ('ftp error', msg), sys.exc_info()[2]
@ -504,7 +512,11 @@ class URLopener:
# mediatype := [ type "/" subtype ] *( ";" parameter )
# data := *urlchar
# parameter := attribute "=" value
import StringIO, mimetools
import mimetools
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
try:
[type, data] = url.split(',', 1)
except ValueError:
@ -530,7 +542,7 @@ class URLopener:
msg.append('')
msg.append(data)
msg = '\n'.join(msg)
f = StringIO.StringIO(msg)
f = StringIO(msg)
headers = mimetools.Message(f, 0)
f.fileno = None # needed for addinfourl
return addinfourl(f, headers, url)
@ -697,8 +709,11 @@ def noheaders():
global _noheaders
if _noheaders is None:
import mimetools
import StringIO
_noheaders = mimetools.Message(StringIO.StringIO(), 0)
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
_noheaders = mimetools.Message(StringIO(), 0)
_noheaders.fp.close() # Recycle file descriptor
return _noheaders