Vega strike Python Modules doc  0.5.1
Documentation of the " Modules " folder of Vega strike
 All Data Structures Namespaces Files Functions Variables
urllib Namespace Reference

Data Structures

class  URLopener
 
class  FancyURLopener
 
class  ftpwrapper
 
class  addbase
 
class  addclosehook
 
class  addinfo
 
class  addinfourl
 

Functions

def url2pathname
 
def pathname2url
 
def urlopen
 
def urlretrieve
 
def urlcleanup
 
def localhost
 
def thishost
 
def ftperrors
 
def noheaders
 
def basejoin
 
def toBytes
 
def unwrap
 
def splittype
 
def splithost
 
def splituser
 
def splitpasswd
 
def splitport
 
def splitnport
 
def splitquery
 
def splittag
 
def splitattr
 
def splitvalue
 
def splitgophertype
 
def unquote
 
def unquote_plus
 
def quote
 
def quote_plus
 
def urlencode
 
def getproxies_environment
 
def getproxies
 
def proxy_bypass
 
def getproxies_registry
 
def test1
 
def reporthook
 
def test
 
def main
 

Variables

list __all__
 
string __version__ = '1.15'
 
int MAXFTPCACHE = 10
 
 _urlopener = None
 
dictionary ftpcache = {}
 
 _localhost = None
 
 _thishost = None
 
 _ftperrors = None
 
 _noheaders = None
 
 _typeprog = None
 
 _hostprog = None
 
 _userprog = None
 
 _passwdprog = None
 
 _portprog = None
 
 _nportprog = None
 
 _queryprog = None
 
 _tagprog = None
 
 _valueprog = None
 
tuple always_safe
 
string _fast_safe_test = always_safe+'/'
 
 _fast_safe = None
 
 getproxies = getproxies_environment
 
tuple fp = open(fn, 'rb')
 'gopher://gopher.micro.umn.edu/1/', More...
 
tuple data = fp.read()
 
tuple table = string.maketrans("", "")
 

Detailed Description

Open an arbitrary URL.

See the following document for more info on URLs:
"Names and Addresses, URIs, URLs, URNs, URCs", at
http://www.w3.org/pub/WWW/Addressing/Overview.html

See also the HTTP spec (from which the error codes are derived):
"HTTP - Hypertext Transfer Protocol", at
http://www.w3.org/pub/WWW/Protocols/

Related standards and specs:
- RFC1808: the "relative URL" spec. (authoritative status)
- RFC1738 - the "URL standard". (authoritative status)
- RFC1630 - the "URI spec". (informational status)

The object returned by URLopener().open(file) will differ per
protocol.  All you know is that is has methods read(), readline(),
readlines(), fileno(), close() and info().  The read*(), fileno()
and close() methods work like those of open files.
The info() method returns a mimetools.Message object which can be
used to query various info about the object, if available.
(mimetools.Message objects are queried with the getheader() method.)

Function Documentation

def urllib.basejoin (   base,
  url 
)
Utility to combine a URL with a base URL to form a new URL.

Definition at line 828 of file urllib.py.

References string.rfind(), splithost(), splitquery(), splittag(), and splittype().

829 def basejoin(base, url):
830  """Utility to combine a URL with a base URL to form a new URL."""
831  type, path = splittype(url)
832  if type:
833  # if url is complete (i.e., it contains a type), return it
834  return url
835  host, path = splithost(path)
836  type, basepath = splittype(base) # inherit type from base
837  if host:
838  # if url contains host, just inherit type
839  if type: return type + '://' + host + path
840  else:
841  # no type inherited, so url must have started with //
842  # just return it
843  return url
844  host, basepath = splithost(basepath) # inherit host
845  basepath, basetag = splittag(basepath) # remove extraneous cruft
846  basepath, basequery = splitquery(basepath) # idem
847  if path[:1] != '/':
848  # non-absolute path name
849  if path[:1] in ('#', '?'):
850  # path is just a tag or query, attach to basepath
851  i = len(basepath)
852  else:
853  # else replace last component
854  i = basepath.rfind('/')
855  if i < 0:
856  # basepath not absolute
857  if host:
858  # host present, make absolute
859  basepath = '/'
860  else:
861  # else keep non-absolute
862  basepath = ''
863  else:
864  # remove last file component
865  basepath = basepath[:i+1]
866  # Interpret ../ (important because of symlinks)
867  while basepath and path[:3] == '../':
868  path = path[3:]
869  i = basepath[:-1].rfind('/')
870  if i > 0:
871  basepath = basepath[:i+1]
872  elif i == 0:
873  basepath = '/'
874  break
875  else:
876  basepath = ''
877 
878  path = basepath + path
879  if host and path and path[0] != '/':
880  path = '/' + path
881  if type and host: return type + '://' + host + path
882  elif type: return type + ':' + path
883  elif host: return '//' + host + path # don't know what this means
884  else: return path
885 
886 
887 # Utilities to parse URLs (most of these return None for missing parts):
888 # unwrap('<URL:type://host/path>') --> 'type://host/path'
889 # splittype('type:opaquestring') --> 'type', 'opaquestring'
890 # splithost('//host[:port]/path') --> 'host[:port]', '/path'
891 # splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
892 # splitpasswd('user:passwd') -> 'user', 'passwd'
893 # splitport('host:port') --> 'host', 'port'
894 # splitquery('/path?query') --> '/path', 'query'
895 # splittag('/path#tag') --> '/path', 'tag'
896 # splitattr('/path;attr1=value1;attr2=value2;...') ->
897 # '/path', ['attr1=value1', 'attr2=value2', ...]
898 # splitvalue('attr=value') --> 'attr', 'value'
899 # splitgophertype('/Xselector') --> 'X', 'selector'
900 # unquote('abc%20def') -> 'abc def'
901 # quote('abc def') -> 'abc%20def')
def urllib.ftperrors ( )
Return the set of errors raised by the FTP class.

Definition at line 671 of file urllib.py.

672 def ftperrors():
673  """Return the set of errors raised by the FTP class."""
674  global _ftperrors
675  if not _ftperrors:
676  import ftplib
677  _ftperrors = ftplib.all_errors
678  return _ftperrors
def urllib.getproxies ( )
Return a dictionary of scheme -> proxy server URL mappings.

By convention the mac uses Internet Config to store
proxies.  An HTTP proxy, for instance, is stored under
the HttpProxy key.
Return a dictionary of scheme -> proxy server URL mappings.

Returns settings gathered from the environment, if specified,
or the registry.

Definition at line 1224 of file urllib.py.

References getproxies.

1225  def getproxies():
1226  """Return a dictionary of scheme -> proxy server URL mappings.
1227 
1228  By convention the mac uses Internet Config to store
1229  proxies. An HTTP proxy, for instance, is stored under
1230  the HttpProxy key.
1231 
1232  """
1233  try:
1234  import ic
1235  except ImportError:
1236  return {}
1237 
1238  try:
1239  config = ic.IC()
1240  except ic.error:
1241  return {}
1242  proxies = {}
1243  # HTTP:
1244  if config.has_key('UseHTTPProxy') and config['UseHTTPProxy']:
1245  try:
1246  value = config['HTTPProxyHost']
1247  except ic.error:
1248  pass
1249  else:
1250  proxies['http'] = 'http://%s' % value
1251  # FTP: XXXX To be done.
1252  # Gopher: XXXX To be done.
1253  return proxies
def urllib.getproxies_environment ( )
Return a dictionary of scheme -> proxy server URL mappings.

Scan the environment for variables named <scheme>_proxy;
this seems to be the standard convention.  If you need a
different way, you can pass a proxies dictionary to the
[Fancy]URLopener constructor.

Definition at line 1207 of file urllib.py.

1209  """Return a dictionary of scheme -> proxy server URL mappings.
1210 
1211  Scan the environment for variables named <scheme>_proxy;
1212  this seems to be the standard convention. If you need a
1213  different way, you can pass a proxies dictionary to the
1214  [Fancy]URLopener constructor.
1215 
1216  """
1217  proxies = {}
1218  for name, value in os.environ.items():
1219  name = name.lower()
1220  if value and name[-6:] == '_proxy':
1221  proxies[name[:-6]] = value
1222  return proxies
def urllib.getproxies_registry ( )
Return a dictionary of scheme -> proxy server URL mappings.

Win32 uses the registry to store proxies.

Definition at line 1258 of file urllib.py.

References getproxies, getproxies_environment(), proxy_bypass(), and locale.str().

1259  def getproxies_registry():
1260  """Return a dictionary of scheme -> proxy server URL mappings.
1261 
1262  Win32 uses the registry to store proxies.
1263 
1264  """
1265  proxies = {}
1266  try:
1267  import _winreg
1268  except ImportError:
1269  # Std module, so should be around - but you never know!
1270  return proxies
1271  try:
1272  internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
1273  r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
1274  proxyEnable = _winreg.QueryValueEx(internetSettings,
1275  'ProxyEnable')[0]
1276  if proxyEnable:
1277  # Returned as Unicode but problems if not converted to ASCII
1278  proxyServer = str(_winreg.QueryValueEx(internetSettings,
1279  'ProxyServer')[0])
1280  if '=' in proxyServer:
1281  # Per-protocol settings
1282  for p in proxyServer.split(';'):
1283  protocol, address = p.split('=', 1)
1284  # See if address has a type:// prefix
1285  import re
1286  if not re.match('^([^/:]+)://', address):
1287  address = '%s://%s' % (protocol, address)
1288  proxies[protocol] = address
1289  else:
1290  # Use one setting for all protocols
1291  if proxyServer[:5] == 'http:':
1292  proxies['http'] = proxyServer
1293  else:
1294  proxies['http'] = 'http://%s' % proxyServer
1295  proxies['ftp'] = 'ftp://%s' % proxyServer
1296  internetSettings.Close()
1297  except (WindowsError, ValueError, TypeError):
1298  # Either registry key not found etc, or the value in an
1299  # unexpected format.
1300  # proxies already set up to be empty so nothing to do
1301  pass
1302  return proxies
def urllib.localhost ( )
Return the IP address of the magic hostname 'localhost'.

Definition at line 655 of file urllib.py.

656 def localhost():
657  """Return the IP address of the magic hostname 'localhost'."""
658  global _localhost
659  if not _localhost:
660  _localhost = socket.gethostbyname('localhost')
661  return _localhost
def urllib.main ( )

Definition at line 1429 of file urllib.py.

References getopt.getopt(), test(), test1(), and urlopen().

1430 def main():
1431  import getopt, sys
1432  try:
1433  opts, args = getopt.getopt(sys.argv[1:], "th")
1434  except getopt.error, msg:
1435  print msg
1436  print "Use -h for help"
1437  return
1438  t = 0
1439  for o, a in opts:
1440  if o == '-t':
1441  t = t + 1
1442  if o == '-h':
1443  print "Usage: python urllib.py [-t] [url ...]"
1444  print "-t runs self-test;",
1445  print "otherwise, contents of urls are printed"
1446  return
1447  if t:
1448  if t > 1:
1449  test1()
1450  test(args)
1451  else:
1452  if not args:
1453  print "Use -h for help"
1454  for url in args:
1455  print urlopen(url).read(),
1456 
# Run test program when run as a script
def urllib.noheaders ( )
Return an empty mimetools.Message object.

Definition at line 680 of file urllib.py.

681 def noheaders():
682  """Return an empty mimetools.Message object."""
683  global _noheaders
684  if not _noheaders:
685  import mimetools
686  import StringIO
687  _noheaders = mimetools.Message(StringIO.StringIO(), 0)
688  _noheaders.fp.close() # Recycle file descriptor
689  return _noheaders
690 
691 
692 # Utility classes
def urllib.pathname2url (   pathname)

Definition at line 55 of file urllib.py.

References quote().

55 
56  def pathname2url(pathname):
57  return quote(pathname)
58 
59 # This really consists of two pieces:
60 # (1) a class which handles opening of all sorts of URLs
61 # (plus assorted utilities etc.)
62 # (2) a set of functions for parsing URLs
63 # XXX Should these be separated out into different modules?
64 
65 
# Shortcut for basic usage
def proxy_bypass (   x)

Definition at line 1254 of file urllib.py.

1255  def proxy_bypass(x):
1256  return 0
def urllib.quote (   s,
  safe = '/' 
)
quote('abc def') -> 'abc%20def'

Each part of a URL, e.g. the path info, the query, etc., has a
different set of reserved characters that must be quoted.

RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
the following reserved characters.

reserved    = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
              "$" | ","

Each of these characters is reserved in some component of a URL,
but not necessarily in all of them.

By default, the quote function is intended for quoting the path
section of a URL.  Thus, it will not encode '/'.  This character
is reserved, but in typical usage the quote function is being
called on a path where the existing slash characters are used as
reserved characters.

Definition at line 1101 of file urllib.py.

References dospath.join().

1102 def quote(s, safe = '/'):
1103  """quote('abc def') -> 'abc%20def'
1104 
1105  Each part of a URL, e.g. the path info, the query, etc., has a
1106  different set of reserved characters that must be quoted.
1107 
1108  RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
1109  the following reserved characters.
1110 
1111  reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
1112  "$" | ","
1113 
1114  Each of these characters is reserved in some component of a URL,
1115  but not necessarily in all of them.
1116 
1117  By default, the quote function is intended for quoting the path
1118  section of a URL. Thus, it will not encode '/'. This character
1119  is reserved, but in typical usage the quote function is being
1120  called on a path where the existing slash characters are used as
1121  reserved characters.
1122  """
1123  safe = always_safe + safe
1124  if _fast_safe_test == safe:
1125  return _fast_quote(s)
1126  res = list(s)
1127  for i in range(len(res)):
1128  c = res[i]
1129  if c not in safe:
1130  res[i] = '%%%02X' % ord(c)
1131  return ''.join(res)
def urllib.quote_plus (   s,
  safe = '' 
)
Quote the query fragment of a URL; replacing ' ' with '+'

Definition at line 1132 of file urllib.py.

References dospath.join(), and quote().

1133 def quote_plus(s, safe = ''):
1134  """Quote the query fragment of a URL; replacing ' ' with '+'"""
1135  if ' ' in s:
1136  l = s.split(' ')
1137  for i in range(len(l)):
1138  l[i] = quote(l[i], safe)
1139  return '+'.join(l)
1140  else:
1141  return quote(s, safe)
def urllib.reporthook (   blocknum,
  blocksize,
  totalsize 
)

Definition at line 1390 of file urllib.py.

1391 def reporthook(blocknum, blocksize, totalsize):
1392  # Report during remote transfers
1393  print "Block number: %d, Block size: %d, Total size: %d" % (
1394  blocknum, blocksize, totalsize)
1395 
# Test program
def urllib.splitattr (   url)
splitattr('/path;attr1=value1;attr2=value2;...') ->
    '/path', ['attr1=value1', 'attr2=value2', ...].

Definition at line 1031 of file urllib.py.

1032 def splitattr(url):
1033  """splitattr('/path;attr1=value1;attr2=value2;...') ->
1034  '/path', ['attr1=value1', 'attr2=value2', ...]."""
1035  words = url.split(';')
1036  return words[0], words[1:]
def urllib.splitgophertype (   selector)
splitgophertype('/Xselector') --> 'X', 'selector'.

Definition at line 1049 of file urllib.py.

1050 def splitgophertype(selector):
1051  """splitgophertype('/Xselector') --> 'X', 'selector'."""
1052  if selector[:1] == '/' and selector[1:2]:
1053  return selector[1], selector[2:]
1054  return None, selector
def urllib.splithost (   url)
splithost('//host[:port]/path') --> 'host[:port]', '/path'.

Definition at line 937 of file urllib.py.

938 def splithost(url):
939  """splithost('//host[:port]/path') --> 'host[:port]', '/path'."""
940  global _hostprog
941  if _hostprog is None:
942  import re
943  _hostprog = re.compile('^//([^/]*)(.*)$')
944 
945  match = _hostprog.match(url)
946  if match: return match.group(1, 2)
947  return None, url
def urllib.splitnport (   host,
  defport = -1 
)
Split host and port, returning numeric port.
Return given default port if no ':' found; defaults to -1.
Return numerical port if a valid number are found after ':'.
Return None if ':' but not a valid number.

Definition at line 986 of file urllib.py.

987 def splitnport(host, defport=-1):
988  """Split host and port, returning numeric port.
989  Return given default port if no ':' found; defaults to -1.
990  Return numerical port if a valid number are found after ':'.
991  Return None if ':' but not a valid number."""
992  global _nportprog
993  if _nportprog is None:
994  import re
995  _nportprog = re.compile('^(.*):(.*)$')
996 
997  match = _nportprog.match(host)
998  if match:
999  host, port = match.group(1, 2)
1000  try:
1001  if not port: raise ValueError, "no digits"
1002  nport = int(port)
1003  except ValueError:
1004  nport = None
1005  return host, nport
1006  return host, defport
def urllib.splitpasswd (   user)
splitpasswd('user:passwd') -> 'user', 'passwd'.

Definition at line 961 of file urllib.py.

962 def splitpasswd(user):
963  """splitpasswd('user:passwd') -> 'user', 'passwd'."""
964  global _passwdprog
965  if _passwdprog is None:
966  import re
967  _passwdprog = re.compile('^([^:]*):(.*)$')
968 
969  match = _passwdprog.match(user)
970  if match: return match.group(1, 2)
971  return user, None
972 
# splittag('/path#tag') --> '/path', 'tag'
def urllib.splitport (   host)
splitport('host:port') --> 'host', 'port'.

Definition at line 974 of file urllib.py.

975 def splitport(host):
976  """splitport('host:port') --> 'host', 'port'."""
977  global _portprog
978  if _portprog is None:
979  import re
980  _portprog = re.compile('^(.*):([0-9]+)$')
981 
982  match = _portprog.match(host)
983  if match: return match.group(1, 2)
984  return host, None
def urllib.splitquery (   url)
splitquery('/path?query') --> '/path', 'query'.

Definition at line 1008 of file urllib.py.

1009 def splitquery(url):
1010  """splitquery('/path?query') --> '/path', 'query'."""
1011  global _queryprog
1012  if _queryprog is None:
1013  import re
1014  _queryprog = re.compile('^(.*)\?([^?]*)$')
1015 
1016  match = _queryprog.match(url)
1017  if match: return match.group(1, 2)
1018  return url, None
def urllib.splittag (   url)
splittag('/path#tag') --> '/path', 'tag'.

Definition at line 1020 of file urllib.py.

1021 def splittag(url):
1022  """splittag('/path#tag') --> '/path', 'tag'."""
1023  global _tagprog
1024  if _tagprog is None:
1025  import re
1026  _tagprog = re.compile('^(.*)#([^#]*)$')
1027 
1028  match = _tagprog.match(url)
1029  if match: return match.group(1, 2)
1030  return url, None
def urllib.splittype (   url)
splittype('type:opaquestring') --> 'type', 'opaquestring'.

Definition at line 923 of file urllib.py.

924 def splittype(url):
925  """splittype('type:opaquestring') --> 'type', 'opaquestring'."""
926  global _typeprog
927  if _typeprog is None:
928  import re
929  _typeprog = re.compile('^([^/:]+):')
930 
931  match = _typeprog.match(url)
932  if match:
933  scheme = match.group(1)
934  return scheme.lower(), url[len(scheme) + 1:]
935  return None, url
def urllib.splituser (   host)
splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'.

Definition at line 949 of file urllib.py.

950 def splituser(host):
951  """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
952  global _userprog
953  if _userprog is None:
954  import re
955  _userprog = re.compile('^([^@]*)@(.*)$')
956 
957  match = _userprog.match(host)
958  if match: return map(unquote, match.group(1, 2))
959  return None, host
def urllib.splitvalue (   attr)
splitvalue('attr=value') --> 'attr', 'value'.

Definition at line 1038 of file urllib.py.

1039 def splitvalue(attr):
1040  """splitvalue('attr=value') --> 'attr', 'value'."""
1041  global _valueprog
1042  if _valueprog is None:
1043  import re
1044  _valueprog = re.compile('^([^=]*)=(.*)$')
1045 
1046  match = _valueprog.match(attr)
1047  if match: return match.group(1, 2)
1048  return attr, None
def urllib.test (   args = [])

Definition at line 1396 of file urllib.py.

References urlretrieve().

1397 def test(args=[]):
1398  if not args:
1399  args = [
1400  '/etc/passwd',
1401  'file:/etc/passwd',
1402  'file://localhost/etc/passwd',
'ftp://ftp.python.org/pub/python/README',
def urllib.test1 ( )

Definition at line 1373 of file urllib.py.

References quote(), and unquote().

1374 def test1():
1375  import time
1376  s = ''
1377  for i in range(256): s = s + chr(i)
1378  s = s*4
1379  t0 = time.time()
1380  qs = quote(s)
1381  uqs = unquote(qs)
1382  t1 = time.time()
1383  if uqs != s:
1384  print 'Wrong!'
1385  print `s`
1386  print `qs`
1387  print `uqs`
1388  print round(t1 - t0, 3), 'sec'
1389 
def urllib.thishost ( )
Return the IP address of the current host.

Definition at line 663 of file urllib.py.

664 def thishost():
665  """Return the IP address of the current host."""
666  global _thishost
667  if not _thishost:
668  _thishost = socket.gethostbyname(socket.gethostname())
669  return _thishost
def urllib.toBytes (   url)
toBytes(u"URL") --> 'URL'.

Definition at line 902 of file urllib.py.

903 def toBytes(url):
904  """toBytes(u"URL") --> 'URL'."""
905  # Most URL schemes require ASCII. If that changes, the conversion
906  # can be relaxed
907  if type(url) is types.UnicodeType:
908  try:
909  url = url.encode("ASCII")
910  except UnicodeError:
911  raise UnicodeError("URL " + repr(url) +
912  " contains non-ASCII characters")
913  return url
def urllib.unquote (   s)
unquote('abc%20def') -> 'abc def'.

Definition at line 1055 of file urllib.py.

References dospath.join().

1056 def unquote(s):
1057  """unquote('abc%20def') -> 'abc def'."""
1058  mychr = chr
1059  myatoi = int
1060  list = s.split('%')
1061  res = [list[0]]
1062  myappend = res.append
1063  del list[0]
1064  for item in list:
1065  if item[1:2]:
1066  try:
1067  myappend(mychr(myatoi(item[:2], 16))
1068  + item[2:])
1069  except ValueError:
1070  myappend('%' + item)
1071  else:
1072  myappend('%' + item)
1073  return "".join(res)
def urllib.unquote_plus (   s)
unquote('%7e/abc+def') -> '~/abc def'

Definition at line 1074 of file urllib.py.

References dospath.join(), and unquote().

1075 def unquote_plus(s):
1076  """unquote('%7e/abc+def') -> '~/abc def'"""
1077  if '+' in s:
1078  # replace '+' with ' '
1079  s = ' '.join(s.split('+'))
1080  return unquote(s)
def urllib.unwrap (   url)
unwrap('<URL:type://host/path>') --> 'type://host/path'.

Definition at line 914 of file urllib.py.

References string.strip().

915 def unwrap(url):
916  """unwrap('<URL:type://host/path>') --> 'type://host/path'."""
917  url = url.strip()
918  if url[:1] == '<' and url[-1:] == '>':
919  url = url[1:-1].strip()
920  if url[:4] == 'URL:': url = url[4:].strip()
921  return url
def urllib.url2pathname (   pathname)

Definition at line 53 of file urllib.py.

References unquote().

53 
54  def url2pathname(pathname):
return unquote(pathname)
def urllib.urlcleanup ( )

Definition at line 81 of file urllib.py.

81 
82 def urlcleanup():
83  if _urlopener:
84  _urlopener.cleanup()
85 
def urllib.urlencode (   query,
  doseq = 0 
)
Encode a sequence of two-element tuples or dictionary into a URL query string.

If any values in the query arg are sequences and doseq is true, each
sequence element is converted to a separate parameter.

If the query arg is a sequence of two-element tuples, the order of the
parameters in the output will match the order of parameters in the
input.

Definition at line 1142 of file urllib.py.

References dospath.join(), quote_plus(), and locale.str().

1143 def urlencode(query,doseq=0):
1144  """Encode a sequence of two-element tuples or dictionary into a URL query string.
1145 
1146  If any values in the query arg are sequences and doseq is true, each
1147  sequence element is converted to a separate parameter.
1148 
1149  If the query arg is a sequence of two-element tuples, the order of the
1150  parameters in the output will match the order of parameters in the
1151  input.
1152  """
1153 
1154  if hasattr(query,"items"):
1155  # mapping objects
1156  query = query.items()
1157  else:
1158  # it's a bother at times that strings and string-like objects are
1159  # sequences...
1160  try:
1161  # non-sequence items should not work with len()
1162  x = len(query)
1163  # non-empty strings will fail this
1164  if len(query) and type(query[0]) != types.TupleType:
1165  raise TypeError
1166  # zero-length sequences of all types will get here and succeed,
1167  # but that's a minor nit - since the original implementation
1168  # allowed empty dicts that type of behavior probably should be
1169  # preserved for consistency
1170  except TypeError:
1171  ty,va,tb = sys.exc_info()
1172  raise TypeError, "not a valid non-string sequence or mapping object", tb
1173 
1174  l = []
1175  if not doseq:
1176  # preserve old behavior
1177  for k, v in query:
1178  k = quote_plus(str(k))
1179  v = quote_plus(str(v))
1180  l.append(k + '=' + v)
1181  else:
1182  for k, v in query:
1183  k = quote_plus(str(k))
1184  if type(v) == types.StringType:
1185  v = quote_plus(v)
1186  l.append(k + '=' + v)
1187  elif type(v) == types.UnicodeType:
1188  # is there a reasonable way to convert to ASCII?
1189  # encode generates a string, but "replace" or "ignore"
1190  # lose information and "strict" can raise UnicodeError
1191  v = quote_plus(v.encode("ASCII","replace"))
1192  l.append(k + '=' + v)
1193  else:
1194  try:
1195  # is this a sufficient test for sequence-ness?
1196  x = len(v)
1197  except TypeError:
1198  # not a sequence
1199  v = quote_plus(str(v))
1200  l.append(k + '=' + v)
1201  else:
1202  # loop over the sequence
1203  for elt in v:
1204  l.append(k + '=' + quote_plus(str(elt)))
1205  return '&'.join(l)
1206 
# Proxy handling
def urllib.urlopen (   url,
  data = None 
)
urlopen(url [, data]) -> open file-like object

Definition at line 67 of file urllib.py.

67 
68 def urlopen(url, data=None):
69  """urlopen(url [, data]) -> open file-like object"""
70  global _urlopener
71  if not _urlopener:
72  _urlopener = FancyURLopener()
73  if data is None:
74  return _urlopener.open(url)
75  else:
return _urlopener.open(url, data)
def urllib.urlretrieve (   url,
  filename = None,
  reporthook = None,
  data = None 
)

Definition at line 76 of file urllib.py.

76 
77 def urlretrieve(url, filename=None, reporthook=None, data=None):
78  global _urlopener
79  if not _urlopener:
80  _urlopener = FancyURLopener()
return _urlopener.retrieve(url, filename, reporthook, data)

Variable Documentation

list __all__
Initial value:
1 = ["urlopen", "URLopener", "FancyURLopener", "urlretrieve",
2  "urlcleanup", "quote", "quote_plus", "unquote", "unquote_plus",
3  "urlencode", "url2pathname", "pathname2url", "splittag",
4  "localhost", "thishost", "ftperrors", "basejoin", "unwrap",
5  "splittype", "splithost", "splituser", "splitpasswd", "splitport",
6  "splitnport", "splitquery", "splitattr", "splitvalue",
7  "splitgophertype", "getproxies"]

Definition at line 33 of file urllib.py.

string __version__ = '1.15'

Definition at line 41 of file urllib.py.

_fast_safe = None

Definition at line 1086 of file urllib.py.

string _fast_safe_test = always_safe+'/'

Definition at line 1085 of file urllib.py.

_ftperrors = None

Definition at line 670 of file urllib.py.

_hostprog = None

Definition at line 936 of file urllib.py.

_localhost = None

Definition at line 654 of file urllib.py.

_noheaders = None

Definition at line 679 of file urllib.py.

_nportprog = None

Definition at line 985 of file urllib.py.

_passwdprog = None

Definition at line 960 of file urllib.py.

_portprog = None

Definition at line 973 of file urllib.py.

_queryprog = None

Definition at line 1007 of file urllib.py.

_tagprog = None

Definition at line 1019 of file urllib.py.

_thishost = None

Definition at line 662 of file urllib.py.

_typeprog = None

Definition at line 922 of file urllib.py.

_urlopener = None

Definition at line 66 of file urllib.py.

_userprog = None

Definition at line 948 of file urllib.py.

_valueprog = None

Definition at line 1037 of file urllib.py.

tuple always_safe
Initial value:
1 = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
2  'abcdefghijklmnopqrstuvwxyz'
3  '0123456789' '_.-')

Definition at line 1081 of file urllib.py.

tuple data = fp.read()

Definition at line 1418 of file urllib.py.

tuple fp = open(fn, 'rb')

'gopher://gopher.micro.umn.edu/1/',

Definition at line 1417 of file urllib.py.

dictionary ftpcache = {}

Definition at line 86 of file urllib.py.

def getproxies = getproxies_environment
Return a dictionary of scheme -> proxy server URL mappings.

Returns settings gathered from the environment, if specified,
or the registry.

Definition at line 1367 of file urllib.py.

int MAXFTPCACHE = 10

Definition at line 43 of file urllib.py.

tuple table = string.maketrans("", "")

Definition at line 1421 of file urllib.py.