blob: ff2561b884ee9d03c82babe16e06ca25601b61a3 [file] [log] [blame]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001# Open an arbitrary URL
2#
3# See the following document for a tentative description of URLs:
4# Uniform Resource Locators Tim Berners-Lee
5# INTERNET DRAFT CERN
6# IETF URL Working Group 14 July 1993
7# draft-ietf-uri-url-01.txt
8#
9# The object returned by URLopener().open(file) will differ per
10# protocol. All you know is that is has methods read(), readline(),
11# readlines(), fileno(), close() and info(). The read*(), fileno()
12# and close() methods work like those of open files.
Guido van Rossumbbb0a051995-08-04 04:29:05 +000013# The info() method returns an mimetools.Message object which can be
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000014# used to query various info about the object, if available.
Guido van Rossumbbb0a051995-08-04 04:29:05 +000015# (mimetools.Message objects are queried with the getheader() method.)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000016
Guido van Rossum7c395db1994-07-04 22:14:49 +000017import string
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000018import socket
19import regex
20
21
Guido van Rossumbbb0a051995-08-04 04:29:05 +000022__version__ = '1.3b1'
Guido van Rossum6cb15a01995-06-22 19:00:13 +000023
24
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000025# This really consists of two pieces:
26# (1) a class which handles opening of all sorts of URLs
27# (plus assorted utilities etc.)
28# (2) a set of functions for parsing URLs
29# XXX Should these be separated out into different modules?
30
31
32# Shortcut for basic usage
33_urlopener = None
34def urlopen(url):
35 global _urlopener
36 if not _urlopener:
Guido van Rossumbbb0a051995-08-04 04:29:05 +000037 _urlopener = FancyURLopener()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000038 return _urlopener.open(url)
39def urlretrieve(url):
40 global _urlopener
41 if not _urlopener:
Guido van Rossumbbb0a051995-08-04 04:29:05 +000042 _urlopener = FancyURLopener()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000043 return _urlopener.retrieve(url)
44def urlcleanup():
45 if _urlopener:
46 _urlopener.cleanup()
47
48
49# Class to open URLs.
50# This is a class rather than just a subroutine because we may need
51# more than one set of global protocol-specific options.
Guido van Rossumbbb0a051995-08-04 04:29:05 +000052# Note -- this is a base class for those who don't want the
53# automatic handling of errors type 302 (relocated) and 401
54# (authorization needed).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000055ftpcache = {}
56class URLopener:
57
58 # Constructor
59 def __init__(self):
Guido van Rossum6cb15a01995-06-22 19:00:13 +000060 server_version = "Python-urllib/%s" % __version__
61 self.addheaders = [('User-agent', server_version)]
Guido van Rossum7aeb4b91994-08-23 13:32:20 +000062 self.tempcache = None
63 # Undocumented feature: if you assign {} to tempcache,
64 # it is used to cache files retrieved with
65 # self.retrieve(). This is not enabled by default
66 # since it does not work for changing documents (and I
67 # haven't got the logic to check expiration headers
68 # yet).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000069 self.ftpcache = ftpcache
70 # Undocumented feature: you can use a different
71 # ftp cache by assigning to the .ftpcache member;
72 # in case you want logically independent URL openers
73
74 def __del__(self):
75 self.close()
76
77 def close(self):
78 self.cleanup()
79
80 def cleanup(self):
81 import os
Guido van Rossum7aeb4b91994-08-23 13:32:20 +000082 if self.tempcache:
83 for url in self.tempcache.keys():
84 try:
85 os.unlink(self.tempcache[url][0])
86 except os.error:
87 pass
88 del self.tempcache[url]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000089
90 # Add a header to be used by the HTTP interface only
91 # e.g. u.addheader('Accept', 'sound/basic')
92 def addheader(self, *args):
93 self.addheaders.append(args)
94
95 # External interface
96 # Use URLopener().open(file) instead of open(file, 'r')
97 def open(self, url):
98 type, url = splittype(unwrap(url))
99 if not type: type = 'file'
100 name = 'open_' + type
101 if '-' in name:
102 import regsub
103 name = regsub.gsub('-', '_', name)
104 if not hasattr(self, name):
105 raise IOError, ('url error', 'unknown url type', type)
106 try:
107 return getattr(self, name)(url)
108 except socket.error, msg:
109 raise IOError, ('socket error', msg)
110
111 # External interface
112 # retrieve(url) returns (filename, None) for a local object
113 # or (tempfilename, headers) for a remote object
114 def retrieve(self, url):
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000115 if self.tempcache and self.tempcache.has_key(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000116 return self.tempcache[url]
117 url1 = unwrap(url)
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000118 if self.tempcache and self.tempcache.has_key(url1):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000119 self.tempcache[url] = self.tempcache[url1]
120 return self.tempcache[url1]
121 type, url1 = splittype(url1)
122 if not type or type == 'file':
123 try:
124 fp = self.open_local_file(url1)
125 del fp
126 return splithost(url1)[1], None
127 except IOError, msg:
128 pass
129 fp = self.open(url)
130 headers = fp.info()
131 import tempfile
132 tfn = tempfile.mktemp()
Guido van Rossumfa59e831994-09-21 11:36:19 +0000133 result = tfn, headers
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000134 if self.tempcache is not None:
Guido van Rossumfa59e831994-09-21 11:36:19 +0000135 self.tempcache[url] = result
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000136 tfp = open(tfn, 'w')
137 bs = 1024*8
138 block = fp.read(bs)
139 while block:
140 tfp.write(block)
141 block = fp.read(bs)
142 del fp
143 del tfp
144 return result
145
146 # Each method named open_<type> knows how to open that type of URL
147
148 # Use HTTP protocol
149 def open_http(self, url):
150 import httplib
151 host, selector = splithost(url)
Guido van Rossum590b2891994-04-18 09:39:56 +0000152 if not host: raise IOError, ('http error', 'no host given')
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000153 i = string.find(host, '@')
154 if i >= 0:
155 user_passwd, host = host[:i], host[i+1:]
156 else:
157 user_passwd = None
158 if user_passwd:
159 import base64
160 auth = string.strip(base64.encodestring(user_passwd))
161 else:
162 auth = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000163 h = httplib.HTTP(host)
164 h.putrequest('GET', selector)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000165 if auth: h.putheader('Authorization: Basic %s' % auth)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000166 for args in self.addheaders: apply(h.putheader, args)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000167 h.endheaders()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000168 errcode, errmsg, headers = h.getreply()
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000169 fp = h.getfile()
170 if errcode == 200:
171 return addinfo(fp, headers)
172 else:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000173 return self.http_error(url,
174 fp, errcode, errmsg, headers)
175
176 # Handle http errors.
177 # Derived class can override this, or provide specific handlers
178 # named http_error_DDD where DDD is the 3-digit error code
179 def http_error(self, url, fp, errcode, errmsg, headers):
180 # First check if there's a specific handler for this error
181 name = 'http_error_%d' % errcode
182 if hasattr(self, name):
183 method = getattr(self, name)
184 result = method(url, fp, errcode, errmsg, headers)
185 if result: return result
186 return self.http_error_default(
187 url, fp, errcode, errmsg, headers)
188
189 # Default http error handler: close the connection and raises IOError
190 def http_error_default(self, url, fp, errcode, errmsg, headers):
191 void = fp.read()
192 fp.close()
193 raise IOError, ('http error', errcode, errmsg, headers)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000194
195 # Use Gopher protocol
196 def open_gopher(self, url):
197 import gopherlib
198 host, selector = splithost(url)
Guido van Rossum590b2891994-04-18 09:39:56 +0000199 if not host: raise IOError, ('gopher error', 'no host given')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000200 type, selector = splitgophertype(selector)
201 selector, query = splitquery(selector)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000202 selector = unquote(selector)
203 if query:
204 query = unquote(query)
205 fp = gopherlib.send_query(selector, query, host)
206 else:
207 fp = gopherlib.send_selector(selector, host)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000208 return addinfo(fp, noheaders())
209
210 # Use local file or FTP depending on form of URL
211 def open_file(self, url):
212 try:
213 return self.open_local_file(url)
214 except IOError:
215 return self.open_ftp(url)
216
217 # Use local file
218 def open_local_file(self, url):
219 host, file = splithost(url)
220 if not host: return addinfo(open(file, 'r'), noheaders())
221 host, port = splitport(host)
222 if not port and socket.gethostbyname(host) in (
223 localhost(), thishost()):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000224 file = unquote(file)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000225 return addinfo(open(file, 'r'), noheaders())
226 raise IOError, ('local file error', 'not on local host')
227
228 # Use FTP protocol
229 def open_ftp(self, url):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000230 host, path = splithost(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000231 if not host: raise IOError, ('ftp error', 'no host given')
232 host, port = splitport(host)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000233 user, host = splituser(host)
234 if user: user, passwd = splitpasswd(user)
235 else: passwd = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000236 host = socket.gethostbyname(host)
237 if not port:
238 import ftplib
239 port = ftplib.FTP_PORT
Guido van Rossum7c395db1994-07-04 22:14:49 +0000240 path, attrs = splitattr(path)
241 dirs = string.splitfields(path, '/')
242 dirs, file = dirs[:-1], dirs[-1]
243 if dirs and not dirs[0]: dirs = dirs[1:]
244 key = (user, host, port, string.joinfields(dirs, '/'))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000245 try:
246 if not self.ftpcache.has_key(key):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000247 self.ftpcache[key] = \
248 ftpwrapper(user, passwd,
249 host, port, dirs)
250 if not file: type = 'D'
251 else: type = 'I'
252 for attr in attrs:
253 attr, value = splitvalue(attr)
254 if string.lower(attr) == 'type' and \
255 value in ('a', 'A', 'i', 'I', 'd', 'D'):
256 type = string.upper(value)
257 return addinfo(self.ftpcache[key].retrfile(file, type),
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000258 noheaders())
259 except ftperrors(), msg:
260 raise IOError, ('ftp error', msg)
261
262
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000263# Derived class with handlers for errors we can handle (perhaps)
264class FancyURLopener(URLopener):
265
266 def __init__(self, *args):
267 apply(URLopener.__init__, (self,) + args)
268 self.auth_cache = {}
269
270 # Default error handling -- don't raise an exception
271 def http_error_default(self, url, fp, errcode, errmsg, headers):
272 return addinfo(fp, headers)
273
274 # Error 302 -- relocated
275 def http_error_302(self, url, fp, errcode, errmsg, headers):
276 # XXX The server can force infinite recursion here!
277 if headers.has_key('location'):
278 newurl = headers['location']
279 elif headers.has_key('uri'):
280 newurl = headers['uri']
281 else:
282 return
283 void = fp.read()
284 fp.close()
285 return self.open(newurl)
286
287 # Error 401 -- authentication required
288 # See this URL for a description of the basic authentication scheme:
289 # http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
290 def http_error_401(self, url, fp, errcode, errmsg, headers):
291 if headers.has_key('www-authenticate'):
292 stuff = headers['www-authenticate']
293 p = regex.compile(
294 '[ \t]*\([^ \t]+\)[ \t]+realm="\([^"]*\)"')
295 if p.match(stuff) >= 0:
296 scheme, realm = p.group(1, 2)
297 if string.lower(scheme) == 'basic':
298 return self.retry_http_basic_auth(
299 url, realm)
300
301 def retry_http_basic_auth(self, url, realm):
302 host, selector = splithost(url)
303 i = string.find(host, '@') + 1
304 host = host[i:]
305 user, passwd = self.get_user_passwd(host, realm, i)
306 if not (user or passwd): return None
307 host = user + ':' + passwd + '@' + host
308 newurl = '//' + host + selector
309 return self.open_http(newurl)
310
311 def get_user_passwd(self, host, realm, clear_cache = 0):
312 key = realm + '@' + string.lower(host)
313 if self.auth_cache.has_key(key):
314 if clear_cache:
315 del self.auth_cache[key]
316 else:
317 return self.auth_cache[key]
318 user, passwd = self.prompt_user_passwd(host, realm)
319 if user or passwd: self.auth_cache[key] = (user, passwd)
320 return user, passwd
321
322 def prompt_user_passwd(self, host, realm):
323 # Override this in a GUI environment!
324 try:
325 user = raw_input("Enter username for %s at %s: " %
326 (realm, host))
327 self.echo_off()
328 try:
329 passwd = raw_input(
330 "Enter password for %s in %s at %s: " %
331 (user, realm, host))
332 finally:
333 self.echo_on()
334 return user, passwd
335 except KeyboardInterrupt:
336 return None, None
337
338 def echo_off(self):
339 import os
340 os.system("stty -echo")
341
342 def echo_on(self):
343 import os
344 print
345 os.system("stty echo")
346
347
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000348# Utility functions
349
350# Return the IP address of the magic hostname 'localhost'
351_localhost = None
352def localhost():
353 global _localhost
354 if not _localhost:
355 _localhost = socket.gethostbyname('localhost')
356 return _localhost
357
358# Return the IP address of the current host
359_thishost = None
360def thishost():
361 global _thishost
362 if not _thishost:
363 _thishost = socket.gethostbyname(socket.gethostname())
364 return _thishost
365
366# Return the set of errors raised by the FTP class
367_ftperrors = None
368def ftperrors():
369 global _ftperrors
370 if not _ftperrors:
371 import ftplib
372 _ftperrors = (ftplib.error_reply,
373 ftplib.error_temp,
374 ftplib.error_perm,
375 ftplib.error_proto)
376 return _ftperrors
377
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000378# Return an empty mimetools.Message object
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000379_noheaders = None
380def noheaders():
381 global _noheaders
382 if not _noheaders:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000383 import mimetools
384 import StringIO
385 _noheaders = mimetools.Message(StringIO.StringIO(), 0)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000386 _noheaders.fp.close() # Recycle file descriptor
387 return _noheaders
388
389
390# Utility classes
391
392# Class used by open_ftp() for cache of open FTP connections
393class ftpwrapper:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000394 def __init__(self, user, passwd, host, port, dirs):
395 self.user = unquote(user or '')
396 self.passwd = unquote(passwd or '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000397 self.host = host
398 self.port = port
Guido van Rossum7c395db1994-07-04 22:14:49 +0000399 self.dirs = []
400 for dir in dirs:
401 self.dirs.append(unquote(dir))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000402 self.init()
403 def init(self):
404 import ftplib
405 self.ftp = ftplib.FTP()
406 self.ftp.connect(self.host, self.port)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000407 self.ftp.login(self.user, self.passwd)
408 for dir in self.dirs:
409 self.ftp.cwd(dir)
410 def retrfile(self, file, type):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000411 import ftplib
Guido van Rossum7c395db1994-07-04 22:14:49 +0000412 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
413 else: cmd = 'TYPE ' + type; isdir = 0
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000414 try:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000415 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000416 except ftplib.all_errors:
417 self.init()
Guido van Rossum7c395db1994-07-04 22:14:49 +0000418 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000419 conn = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000420 if file and not isdir:
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000421 try:
422 cmd = 'RETR ' + file
423 conn = self.ftp.transfercmd(cmd)
424 except ftplib.error_perm, reason:
425 if reason[:3] != '550':
426 raise IOError, ('ftp error', reason)
427 if not conn:
428 # Try a directory listing
429 if file: cmd = 'LIST ' + file
430 else: cmd = 'LIST'
431 conn = self.ftp.transfercmd(cmd)
432 return addclosehook(conn.makefile('r'), self.ftp.voidresp)
433
434# Base class for addinfo and addclosehook
435class addbase:
436 def __init__(self, fp):
437 self.fp = fp
438 self.read = self.fp.read
439 self.readline = self.fp.readline
440 self.readlines = self.fp.readlines
441 self.fileno = self.fp.fileno
442 def __repr__(self):
443 return '<%s at %s whose fp = %s>' % (
444 self.__class__.__name__, `id(self)`, `self.fp`)
445 def __del__(self):
446 self.close()
447 def close(self):
448 self.read = None
449 self.readline = None
450 self.readlines = None
451 self.fileno = None
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000452 if self.fp: self.fp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000453 self.fp = None
454
455# Class to add a close hook to an open file
456class addclosehook(addbase):
457 def __init__(self, fp, closehook, *hookargs):
458 addbase.__init__(self, fp)
459 self.closehook = closehook
460 self.hookargs = hookargs
461 def close(self):
462 if self.closehook:
463 apply(self.closehook, self.hookargs)
464 self.closehook = None
465 self.hookargs = None
466 addbase.close(self)
467
468# class to add an info() method to an open file
469class addinfo(addbase):
470 def __init__(self, fp, headers):
471 addbase.__init__(self, fp)
472 self.headers = headers
473 def info(self):
474 return self.headers
475
476
477# Utility to combine a URL with a base URL to form a new URL
478
479def basejoin(base, url):
480 type, path = splittype(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000481 host, path = splithost(path)
Guido van Rossuma1124701994-12-30 17:18:59 +0000482 if type and host: return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000483 basetype, basepath = splittype(base)
484 basehost, basepath = splithost(basepath)
485 basepath, basetag = splittag(basepath)
486 basepath, basequery = splitquery(basepath)
Guido van Rossuma1124701994-12-30 17:18:59 +0000487 if not type: type = basetype or 'file'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000488 if path[:1] != '/':
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000489 i = string.rfind(basepath, '/')
490 if i < 0: basepath = '/'
491 else: basepath = basepath[:i+1]
492 path = basepath + path
493 if not host: host = basehost
494 if host: return type + '://' + host + path
495 else: return type + ':' + path
496
497
Guido van Rossum7c395db1994-07-04 22:14:49 +0000498# Utilities to parse URLs (most of these return None for missing parts):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000499# unwrap('<URL:type//host/path>') --> 'type//host/path'
500# splittype('type:opaquestring') --> 'type', 'opaquestring'
501# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000502# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
503# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000504# splitport('host:port') --> 'host', 'port'
505# splitquery('/path?query') --> '/path', 'query'
506# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000507# splitattr('/path;attr1=value1;attr2=value2;...') ->
508# '/path', ['attr1=value1', 'attr2=value2', ...]
509# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000510# splitgophertype('/Xselector') --> 'X', 'selector'
511# unquote('abc%20def') -> 'abc def'
512# quote('abc def') -> 'abc%20def')
513
514def unwrap(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000515 url = string.strip(url)
516 if url[:1] == '<' and url[-1:] == '>':
517 url = string.strip(url[1:-1])
518 if url[:4] == 'URL:': url = string.strip(url[4:])
519 return url
520
521_typeprog = regex.compile('^\([^/:]+\):\(.*\)$')
522def splittype(url):
523 if _typeprog.match(url) >= 0: return _typeprog.group(1, 2)
524 return None, url
525
526_hostprog = regex.compile('^//\([^/]+\)\(.*\)$')
527def splithost(url):
528 if _hostprog.match(url) >= 0: return _hostprog.group(1, 2)
529 return None, url
530
Guido van Rossum7c395db1994-07-04 22:14:49 +0000531_userprog = regex.compile('^\([^@]*\)@\(.*\)$')
532def splituser(host):
533 if _userprog.match(host) >= 0: return _userprog.group(1, 2)
534 return None, host
535
536_passwdprog = regex.compile('^\([^:]*\):\(.*\)$')
537def splitpasswd(user):
538 if _passwdprog.match(user) >= 0: return _passwdprog.group(1, 2)
539 return user, None
540
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000541_portprog = regex.compile('^\(.*\):\([0-9]+\)$')
542def splitport(host):
543 if _portprog.match(host) >= 0: return _portprog.group(1, 2)
544 return host, None
545
546_queryprog = regex.compile('^\(.*\)\?\([^?]*\)$')
547def splitquery(url):
548 if _queryprog.match(url) >= 0: return _queryprog.group(1, 2)
549 return url, None
550
551_tagprog = regex.compile('^\(.*\)#\([^#]*\)$')
552def splittag(url):
553 if _tagprog.match(url) >= 0: return _tagprog.group(1, 2)
554 return url, None
555
Guido van Rossum7c395db1994-07-04 22:14:49 +0000556def splitattr(url):
557 words = string.splitfields(url, ';')
558 return words[0], words[1:]
559
560_valueprog = regex.compile('^\([^=]*\)=\(.*\)$')
561def splitvalue(attr):
562 if _valueprog.match(attr) >= 0: return _valueprog.group(1, 2)
563 return attr, None
564
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000565def splitgophertype(selector):
566 if selector[:1] == '/' and selector[1:2]:
567 return selector[1], selector[2:]
568 return None, selector
569
570_quoteprog = regex.compile('%[0-9a-fA-F][0-9a-fA-F]')
571def unquote(s):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000572 i = 0
573 n = len(s)
574 res = ''
575 while 0 <= i < n:
576 j = _quoteprog.search(s, i)
577 if j < 0:
578 res = res + s[i:]
579 break
580 res = res + (s[i:j] + chr(eval('0x' + s[j+1:j+3])))
581 i = j+3
582 return res
583
Guido van Rossum3bb54481994-08-29 10:52:58 +0000584always_safe = string.letters + string.digits + '_,.-'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000585def quote(s, safe = '/'):
586 safe = always_safe + safe
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000587 res = ''
588 for c in s:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000589 if c in safe:
590 res = res + c
591 else:
592 res = res + '%%%02x' % ord(c)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000593 return res
594
595# Test and time quote() and unquote()
596def test1():
597 import time
598 s = ''
599 for i in range(256): s = s + chr(i)
600 s = s*4
601 t0 = time.time()
602 qs = quote(s)
603 uqs = unquote(qs)
604 t1 = time.time()
605 if uqs != s:
606 print 'Wrong!'
607 print `s`
608 print `qs`
609 print `uqs`
610 print round(t1 - t0, 3), 'sec'
611
612
613# Test program
614def test():
615 import sys
616 import regsub
617 args = sys.argv[1:]
618 if not args:
619 args = [
620 '/etc/passwd',
621 'file:/etc/passwd',
622 'file://localhost/etc/passwd',
623 'ftp://ftp.cwi.nl/etc/passwd',
624 'gopher://gopher.cwi.nl/11/',
625 'http://www.cwi.nl/index.html',
626 ]
627 try:
628 for url in args:
629 print '-'*10, url, '-'*10
630 fn, h = urlretrieve(url)
631 print fn, h
632 if h:
633 print '======'
634 for k in h.keys(): print k + ':', h[k]
635 print '======'
636 fp = open(fn, 'r')
637 data = fp.read()
638 del fp
639 print regsub.gsub('\r', '', data)
640 fn, h = None, None
641 print '-'*40
642 finally:
643 urlcleanup()
644
645# Run test program when run as a script
646if __name__ == '__main__':
Guido van Rossum7c395db1994-07-04 22:14:49 +0000647## test1()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000648 test()