summaryrefslogtreecommitdiffstats
path: root/Lib/urllib.py
diff options
context:
space:
mode:
authorSkip Montanaro <skip@pobox.com>2001-01-28 21:11:12 (GMT)
committerSkip Montanaro <skip@pobox.com>2001-01-28 21:11:12 (GMT)
commit14f1ad4a949830998435f6cb3860e01046fa0da1 (patch)
tree30724e2acc4e4dd6a2fa7c0398a8723a77df610b /Lib/urllib.py
parent399b8af5637720d91bd503250b362f4717009eca (diff)
downloadcpython-14f1ad4a949830998435f6cb3860e01046fa0da1.zip
cpython-14f1ad4a949830998435f6cb3860e01046fa0da1.tar.gz
cpython-14f1ad4a949830998435f6cb3860e01046fa0da1.tar.bz2
allow first param urlencode to be a sequence of two-element tuples - in this
case, the order of parameters in the output matches the order of the inputs.
Diffstat (limited to 'Lib/urllib.py')
-rw-r--r--Lib/urllib.py35
1 files changed, 30 insertions, 5 deletions
diff --git a/Lib/urllib.py b/Lib/urllib.py
index f096151..a410e71 100644
--- a/Lib/urllib.py
+++ b/Lib/urllib.py
@@ -1093,21 +1093,46 @@ def quote_plus(s, safe = ''):
else:
return quote(s, safe)
-def urlencode(dict,doseq=0):
- """Encode a dictionary of form entries into a URL query string.
+def urlencode(query,doseq=0):
+ """Encode a sequence of two-element tuples or dictionary into a URL query string.
- If any values in the dict are sequences and doseq is true, each
+ 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.
"""
+
+ if hasattr(query,"items"):
+ # mapping objects
+ query = query.items()
+ else:
+ # it's a bother at times that strings and string-like objects are
+ # sequences...
+ try:
+ # non-sequence items should not work with len()
+ x = len(query)
+ # non-empty strings will fail this
+ if len(query) and type(query[0]) != types.TupleType:
+ raise TypeError
+ # zero-length sequences of all types will get here and succeed,
+ # but that's a minor nit - since the original implementation
+ # allowed empty dicts that type of behavior probably should be
+ # preserved for consistency
+ except TypeError:
+ ty,va,tb = sys.exc_info()
+ raise TypeError, "not a valid non-string sequence or mapping object", tb
+
l = []
if not doseq:
# preserve old behavior
- for k, v in dict.items():
+ for k, v in query:
k = quote_plus(str(k))
v = quote_plus(str(v))
l.append(k + '=' + v)
else:
- for k, v in dict.items():
+ for k, v in query:
k = quote_plus(str(k))
if type(v) == types.StringType:
v = quote_plus(v)