Change by Sjoerd (with minor reformatting):

guess the mime type of a local file.

Change suggested by Sjoerd (with different implementation):
  when retrieve() creates a temporary file, preserve the suffix.

Corrollary of the first change:
  also return the mime type of a local file in retrieve().
This commit is contained in:
Guido van Rossum 1998-04-03 15:56:16 +00:00
parent fcc6c68e11
commit b5916ab065
1 changed files with 18 additions and 4 deletions

View File

@ -178,15 +178,25 @@ class URLopener:
if not filename and (not type or type == 'file'):
try:
fp = self.open_local_file(url1)
hdrs = fp.info()
del fp
return url2pathname(splithost(url1)[1]), None
return url2pathname(splithost(url1)[1]), hdrs
except IOError, msg:
pass
fp = self.open(url)
headers = fp.info()
if not filename:
import tempfile
filename = tempfile.mktemp()
garbage, path = splittype(url)
print (garbage, path)
garbage, path = splithost(path or "")
print (garbage, path)
path, garbage = splitquery(path or "")
print (path, garbage)
path, garbage = splitattr(path or "")
print (path, garbage)
suffix = os.path.splitext(path)[1]
filename = tempfile.mktemp(suffix)
self.__tempfiles.append(filename)
result = filename, headers
if self.tempcache is not None:
@ -297,18 +307,22 @@ class URLopener:
# Use local file
def open_local_file(self, url):
import mimetypes, mimetools, StringIO
mtype = mimetypes.guess_type(url)[0]
headers = mimetools.Message(StringIO.StringIO(
'Content-Type: %s\n' % (mtype or 'text/plain')))
host, file = splithost(url)
if not host:
return addinfourl(
open(url2pathname(file), 'rb'),
noheaders(), 'file:'+file)
headers, 'file:'+file)
host, port = splitport(host)
if not port and socket.gethostbyname(host) in (
localhost(), thishost()):
file = unquote(file)
return addinfourl(
open(url2pathname(file), 'rb'),
noheaders(), 'file:'+file)
headers, 'file:'+file)
raise IOError, ('local file error', 'not on local host')
# Use FTP protocol