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 parame
(query,doseq=False,)
| 164 | # Python 2.1 CVS maintenance branch of urllib. It will accept a sequence |
| 165 | # of pairs instead of a mapping -- the 2.0 version only accepts a mapping. |
| 166 | def urlencode(query,doseq=False,): |
| 167 | """Encode a sequence of two-element tuples or dictionary into a URL query \ |
| 168 | string. |
| 169 | |
| 170 | If any values in the query arg are sequences and doseq is true, each |
| 171 | sequence element is converted to a separate parameter. |
| 172 | |
| 173 | If the query arg is a sequence of two-element tuples, the order of the |
| 174 | parameters in the output will match the order of parameters in the |
| 175 | input. |
| 176 | """ |
| 177 | |
| 178 | if hasattr(query,"items"): |
| 179 | # mapping objects |
| 180 | query = query.items() |
| 181 | else: |
| 182 | # it's a bother at times that strings and string-like objects are |
| 183 | # sequences... |
| 184 | try: |
| 185 | # non-sequence items should not work with len() |
| 186 | x = len(query) |
| 187 | # non-empty strings will fail this |
| 188 | if len(query) and type(query[0]) != tuple: |
| 189 | raise TypeError() |
| 190 | # zero-length sequences of all types will get here and succeed, |
| 191 | # but that's a minor nit - since the original implementation |
| 192 | # allowed empty dicts that type of behavior probably should be |
| 193 | # preserved for consistency |
| 194 | except TypeError: |
| 195 | ty,va,tb = sys.exc_info() |
| 196 | raise TypeError("not a valid non-string sequence or mapping " |
| 197 | "object", tb) |
| 198 | |
| 199 | l = [] |
| 200 | if not doseq: |
| 201 | # preserve old behavior |
| 202 | for k, v in query: |
| 203 | k = _quote_plus(k) |
| 204 | v = _quote_plus(v) |
| 205 | l.append(k + '=' + v) |
| 206 | else: |
| 207 | for k, v in query: |
| 208 | k = _quote_plus(k) |
| 209 | if isinstance(v, six.string_types): |
| 210 | v = _quote_plus(v) |
| 211 | l.append(k + '=' + v) |
| 212 | else: |
| 213 | try: |
| 214 | # is this a sufficient test for sequence-ness? |
| 215 | x = len(v) |
| 216 | except TypeError: |
| 217 | # not a sequence |
| 218 | v = _quote_plus(v) |
| 219 | l.append(k + '=' + v) |
| 220 | else: |
| 221 | # loop over the sequence |
| 222 | for elt in v: |
| 223 | l.append(k + '=' + _quote_plus(elt)) |
no test coverage detected
searching dependent graphs…