| 1 |
|
| 2 |
|
| 3 |
""" |
| 4 |
requests.utils |
| 5 |
~~~~~~~~~~~~~~ |
| 6 |
|
| 7 |
This module provides utility functions that are used within Requests |
| 8 |
that are also useful for external consumption. |
| 9 |
|
| 10 |
""" |
| 11 |
|
| 12 |
import cgi |
| 13 |
import codecs |
| 14 |
import os |
| 15 |
import platform |
| 16 |
import re |
| 17 |
import sys |
| 18 |
import zlib |
| 19 |
from netrc import netrc, NetrcParseError |
| 20 |
|
| 21 |
from . import __version__ |
| 22 |
from . import certs |
| 23 |
from .compat import parse_http_list as _parse_list_header |
| 24 |
from .compat import quote, urlparse, bytes, str, OrderedDict, urlunparse |
| 25 |
from .cookies import RequestsCookieJar, cookiejar_from_dict |
| 26 |
|
| 27 |
_hush_pyflakes = (RequestsCookieJar,) |
| 28 |
|
| 29 |
NETRC_FILES = ('.netrc', '_netrc') |
| 30 |
|
| 31 |
DEFAULT_CA_BUNDLE_PATH = certs.where() |
| 32 |
|
| 33 |
|
| 34 |
def dict_to_sequence(d): |
| 35 |
"""Returns an internal sequence dictionary update.""" |
| 36 |
|
| 37 |
if hasattr(d, 'items'): |
| 38 |
d = d.items() |
| 39 |
|
| 40 |
return d |
| 41 |
|
| 42 |
|
| 43 |
def super_len(o): |
| 44 |
if hasattr(o, '__len__'): |
| 45 |
return len(o) |
| 46 |
if hasattr(o, 'len'): |
| 47 |
return o.len |
| 48 |
if hasattr(o, 'fileno'): |
| 49 |
return os.fstat(o.fileno()).st_size |
| 50 |
|
| 51 |
|
| 52 |
def get_netrc_auth(url): |
| 53 |
"""Returns the Requests tuple auth for a given url from netrc.""" |
| 54 |
|
| 55 |
try: |
| 56 |
locations = (os.path.expanduser('~/{0}'.format(f)) for f in NETRC_FILES) |
| 57 |
netrc_path = None |
| 58 |
|
| 59 |
for loc in locations: |
| 60 |
if os.path.exists(loc) and not netrc_path: |
| 61 |
netrc_path = loc |
| 62 |
|
| 63 |
|
| 64 |
if netrc_path is None: |
| 65 |
return netrc_path |
| 66 |
|
| 67 |
ri = urlparse(url) |
| 68 |
|
| 69 |
|
| 70 |
host = ri.netloc.split(':')[0] |
| 71 |
|
| 72 |
try: |
| 73 |
_netrc = netrc(netrc_path).authenticators(host) |
| 74 |
if _netrc: |
| 75 |
|
| 76 |
login_i = (0 if _netrc[0] else 1) |
| 77 |
return (_netrc[login_i], _netrc[2]) |
| 78 |
except (NetrcParseError, IOError): |
| 79 |
|
| 80 |
|
| 81 |
pass |
| 82 |
|
| 83 |
|
| 84 |
except (ImportError, AttributeError): |
| 85 |
pass |
| 86 |
|
| 87 |
|
| 88 |
def guess_filename(obj): |
| 89 |
"""Tries to guess the filename of the given object.""" |
| 90 |
name = getattr(obj, 'name', None) |
| 91 |
if name and name[0] != '<' and name[-1] != '>': |
| 92 |
return os.path.basename(name) |
| 93 |
|
| 94 |
|
| 95 |
def from_key_val_list(value): |
| 96 |
"""Take an object and test to see if it can be represented as a |
| 97 |
dictionary. Unless it can not be represented as such, return an |
| 98 |
OrderedDict, e.g., |
| 99 |
|
| 100 |
:: |
| 101 |
|
| 102 |
>>> from_key_val_list([('key', 'val')]) |
| 103 |
OrderedDict([('key', 'val')]) |
| 104 |
>>> from_key_val_list('string') |
| 105 |
ValueError: need more than 1 value to unpack |
| 106 |
>>> from_key_val_list({'key': 'val'}) |
| 107 |
OrderedDict([('key', 'val')]) |
| 108 |
""" |
| 109 |
if value is None: |
| 110 |
return None |
| 111 |
|
| 112 |
if isinstance(value, (str, bytes, bool, int)): |
| 113 |
raise ValueError('cannot encode objects that are not 2-tuples') |
| 114 |
|
| 115 |
return OrderedDict(value) |
| 116 |
|
| 117 |
|
| 118 |
def to_key_val_list(value): |
| 119 |
"""Take an object and test to see if it can be represented as a |
| 120 |
dictionary. If it can be, return a list of tuples, e.g., |
| 121 |
|
| 122 |
:: |
| 123 |
|
| 124 |
>>> to_key_val_list([('key', 'val')]) |
| 125 |
[('key', 'val')] |
| 126 |
>>> to_key_val_list({'key': 'val'}) |
| 127 |
[('key', 'val')] |
| 128 |
>>> to_key_val_list('string') |
| 129 |
ValueError: cannot encode objects that are not 2-tuples. |
| 130 |
""" |
| 131 |
if value is None: |
| 132 |
return None |
| 133 |
|
| 134 |
if isinstance(value, (str, bytes, bool, int)): |
| 135 |
raise ValueError('cannot encode objects that are not 2-tuples') |
| 136 |
|
| 137 |
if isinstance(value, dict): |
| 138 |
value = value.items() |
| 139 |
|
| 140 |
return list(value) |
| 141 |
|
| 142 |
|
| 143 |
|
| 144 |
def parse_list_header(value): |
| 145 |
"""Parse lists as described by RFC 2068 Section 2. |
| 146 |
|
| 147 |
In particular, parse comma-separated lists where the elements of |
| 148 |
the list may include quoted-strings. A quoted-string could |
| 149 |
contain a comma. A non-quoted string could have quotes in the |
| 150 |
middle. Quotes are removed automatically after parsing. |
| 151 |
|
| 152 |
It basically works like :func:`parse_set_header` just that items |
| 153 |
may appear multiple times and case sensitivity is preserved. |
| 154 |
|
| 155 |
The return value is a standard :class:`list`: |
| 156 |
|
| 157 |
>>> parse_list_header('token, "quoted value"') |
| 158 |
['token', 'quoted value'] |
| 159 |
|
| 160 |
To create a header from the :class:`list` again, use the |
| 161 |
:func:`dump_header` function. |
| 162 |
|
| 163 |
:param value: a string with a list header. |
| 164 |
:return: :class:`list` |
| 165 |
""" |
| 166 |
result = [] |
| 167 |
for item in _parse_list_header(value): |
| 168 |
if item[:1] == item[-1:] == '"': |
| 169 |
item = unquote_header_value(item[1:-1]) |
| 170 |
result.append(item) |
| 171 |
return result |
| 172 |
|
| 173 |
|
| 174 |
|
| 175 |
def parse_dict_header(value): |
| 176 |
"""Parse lists of key, value pairs as described by RFC 2068 Section 2 and |
| 177 |
convert them into a python dict: |
| 178 |
|
| 179 |
>>> d = parse_dict_header('foo="is a fish", bar="as well"') |
| 180 |
>>> type(d) is dict |
| 181 |
True |
| 182 |
>>> sorted(d.items()) |
| 183 |
[('bar', 'as well'), ('foo', 'is a fish')] |
| 184 |
|
| 185 |
If there is no value for a key it will be `None`: |
| 186 |
|
| 187 |
>>> parse_dict_header('key_without_value') |
| 188 |
{'key_without_value': None} |
| 189 |
|
| 190 |
To create a header from the :class:`dict` again, use the |
| 191 |
:func:`dump_header` function. |
| 192 |
|
| 193 |
:param value: a string with a dict header. |
| 194 |
:return: :class:`dict` |
| 195 |
""" |
| 196 |
result = {} |
| 197 |
for item in _parse_list_header(value): |
| 198 |
if '=' not in item: |
| 199 |
result[item] = None |
| 200 |
continue |
| 201 |
name, value = item.split('=', 1) |
| 202 |
if value[:1] == value[-1:] == '"': |
| 203 |
value = unquote_header_value(value[1:-1]) |
| 204 |
result[name] = value |
| 205 |
return result |
| 206 |
|
| 207 |
|
| 208 |
|
| 209 |
def unquote_header_value(value, is_filename=False): |
| 210 |
r"""Unquotes a header value. (Reversal of :func:`quote_header_value`). |
| 211 |
This does not use the real unquoting but what browsers are actually |
| 212 |
using for quoting. |
| 213 |
|
| 214 |
:param value: the header value to unquote. |
| 215 |
""" |
| 216 |
if value and value[0] == value[-1] == '"': |
| 217 |
|
| 218 |
|
| 219 |
|
| 220 |
|
| 221 |
value = value[1:-1] |
| 222 |
|
| 223 |
|
| 224 |
|
| 225 |
|
| 226 |
|
| 227 |
|
| 228 |
if not is_filename or value[:2] != '\\\\': |
| 229 |
return value.replace('\\\\', '\\').replace('\\"', '"') |
| 230 |
return value |
| 231 |
|
| 232 |
|
| 233 |
def dict_from_cookiejar(cj): |
| 234 |
"""Returns a key/value dictionary from a CookieJar. |
| 235 |
|
| 236 |
:param cj: CookieJar object to extract cookies from. |
| 237 |
""" |
| 238 |
|
| 239 |
cookie_dict = {} |
| 240 |
|
| 241 |
for cookie in cj: |
| 242 |
cookie_dict[cookie.name] = cookie.value |
| 243 |
|
| 244 |
return cookie_dict |
| 245 |
|
| 246 |
|
| 247 |
def add_dict_to_cookiejar(cj, cookie_dict): |
| 248 |
"""Returns a CookieJar from a key/value dictionary. |
| 249 |
|
| 250 |
:param cj: CookieJar to insert cookies into. |
| 251 |
:param cookie_dict: Dict of key/values to insert into CookieJar. |
| 252 |
""" |
| 253 |
|
| 254 |
cj2 = cookiejar_from_dict(cookie_dict) |
| 255 |
cj.update(cj2) |
| 256 |
return cj |
| 257 |
|
| 258 |
|
| 259 |
def get_encodings_from_content(content): |
| 260 |
"""Returns encodings from given content string. |
| 261 |
|
| 262 |
:param content: bytestring to extract encodings from. |
| 263 |
""" |
| 264 |
|
| 265 |
charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I) |
| 266 |
|
| 267 |
return charset_re.findall(content) |
| 268 |
|
| 269 |
|
| 270 |
def get_encoding_from_headers(headers): |
| 271 |
"""Returns encodings from given HTTP Header Dict. |
| 272 |
|
| 273 |
:param headers: dictionary to extract encoding from. |
| 274 |
""" |
| 275 |
|
| 276 |
content_type = headers.get('content-type') |
| 277 |
|
| 278 |
if not content_type: |
| 279 |
return None |
| 280 |
|
| 281 |
content_type, params = cgi.parse_header(content_type) |
| 282 |
|
| 283 |
if 'charset' in params: |
| 284 |
return params['charset'].strip("'\"") |
| 285 |
|
| 286 |
if 'text' in content_type: |
| 287 |
return 'ISO-8859-1' |
| 288 |
|
| 289 |
|
| 290 |
def stream_decode_response_unicode(iterator, r): |
| 291 |
"""Stream decodes a iterator.""" |
| 292 |
|
| 293 |
if r.encoding is None: |
| 294 |
for item in iterator: |
| 295 |
yield item |
| 296 |
return |
| 297 |
|
| 298 |
decoder = codecs.getincrementaldecoder(r.encoding)(errors='replace') |
| 299 |
for chunk in iterator: |
| 300 |
rv = decoder.decode(chunk) |
| 301 |
if rv: |
| 302 |
yield rv |
| 303 |
rv = decoder.decode('', final=True) |
| 304 |
if rv: |
| 305 |
yield rv |
| 306 |
|
| 307 |
|
| 308 |
def iter_slices(string, slice_length): |
| 309 |
"""Iterate over slices of a string.""" |
| 310 |
pos = 0 |
| 311 |
while pos < len(string): |
| 312 |
yield string[pos:pos + slice_length] |
| 313 |
pos += slice_length |
| 314 |
|
| 315 |
|
| 316 |
def get_unicode_from_response(r): |
| 317 |
"""Returns the requested content back in unicode. |
| 318 |
|
| 319 |
:param r: Response object to get unicode content from. |
| 320 |
|
| 321 |
Tried: |
| 322 |
|
| 323 |
1. charset from content-type |
| 324 |
|
| 325 |
2. every encodings from ``<meta ... charset=XXX>`` |
| 326 |
|
| 327 |
3. fall back and replace all unicode characters |
| 328 |
|
| 329 |
""" |
| 330 |
|
| 331 |
tried_encodings = [] |
| 332 |
|
| 333 |
|
| 334 |
encoding = get_encoding_from_headers(r.headers) |
| 335 |
|
| 336 |
if encoding: |
| 337 |
try: |
| 338 |
return str(r.content, encoding) |
| 339 |
except UnicodeError: |
| 340 |
tried_encodings.append(encoding) |
| 341 |
|
| 342 |
|
| 343 |
try: |
| 344 |
return str(r.content, encoding, errors='replace') |
| 345 |
except TypeError: |
| 346 |
return r.content |
| 347 |
|
| 348 |
|
| 349 |
def stream_decompress(iterator, mode='gzip'): |
| 350 |
"""Stream decodes an iterator over compressed data |
| 351 |
|
| 352 |
:param iterator: An iterator over compressed data |
| 353 |
:param mode: 'gzip' or 'deflate' |
| 354 |
:return: An iterator over decompressed data |
| 355 |
""" |
| 356 |
|
| 357 |
if mode not in ['gzip', 'deflate']: |
| 358 |
raise ValueError('stream_decompress mode must be gzip or deflate') |
| 359 |
|
| 360 |
zlib_mode = 16 + zlib.MAX_WBITS if mode == 'gzip' else -zlib.MAX_WBITS |
| 361 |
dec = zlib.decompressobj(zlib_mode) |
| 362 |
try: |
| 363 |
for chunk in iterator: |
| 364 |
rv = dec.decompress(chunk) |
| 365 |
if rv: |
| 366 |
yield rv |
| 367 |
except zlib.error: |
| 368 |
|
| 369 |
yield chunk |
| 370 |
|
| 371 |
for chunk in iterator: |
| 372 |
yield chunk |
| 373 |
else: |
| 374 |
|
| 375 |
buf = dec.decompress(bytes()) |
| 376 |
rv = buf + dec.flush() |
| 377 |
if rv: |
| 378 |
yield rv |
| 379 |
|
| 380 |
|
| 381 |
def stream_untransfer(gen, resp): |
| 382 |
ce = resp.headers.get('content-encoding', '').lower() |
| 383 |
if 'gzip' in ce: |
| 384 |
gen = stream_decompress(gen, mode='gzip') |
| 385 |
elif 'deflate' in ce: |
| 386 |
gen = stream_decompress(gen, mode='deflate') |
| 387 |
|
| 388 |
return gen |
| 389 |
|
| 390 |
|
| 391 |
|
| 392 |
UNRESERVED_SET = frozenset( |
| 393 |
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" |
| 394 |
+ "0123456789-._~") |
| 395 |
|
| 396 |
|
| 397 |
def unquote_unreserved(uri): |
| 398 |
"""Un-escape any percent-escape sequences in a URI that are unreserved |
| 399 |
characters. This leaves all reserved, illegal and non-ASCII bytes encoded. |
| 400 |
""" |
| 401 |
parts = uri.split('%') |
| 402 |
for i in range(1, len(parts)): |
| 403 |
h = parts[i][0:2] |
| 404 |
if len(h) == 2 and h.isalnum(): |
| 405 |
c = chr(int(h, 16)) |
| 406 |
if c in UNRESERVED_SET: |
| 407 |
parts[i] = c + parts[i][2:] |
| 408 |
else: |
| 409 |
parts[i] = '%' + parts[i] |
| 410 |
else: |
| 411 |
parts[i] = '%' + parts[i] |
| 412 |
return ''.join(parts) |
| 413 |
|
| 414 |
|
| 415 |
def requote_uri(uri): |
| 416 |
"""Re-quote the given URI. |
| 417 |
|
| 418 |
This function passes the given URI through an unquote/quote cycle to |
| 419 |
ensure that it is fully and consistently quoted. |
| 420 |
""" |
| 421 |
|
| 422 |
|
| 423 |
|
| 424 |
return quote(unquote_unreserved(uri), safe="!#$%&'()*+,/:;=?@[]~") |
| 425 |
|
| 426 |
|
| 427 |
def get_environ_proxies(url): |
| 428 |
"""Return a dict of environment proxies.""" |
| 429 |
|
| 430 |
proxy_keys = [ |
| 431 |
'all', |
| 432 |
'http', |
| 433 |
'https', |
| 434 |
'ftp', |
| 435 |
'socks' |
| 436 |
] |
| 437 |
|
| 438 |
get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper()) |
| 439 |
|
| 440 |
|
| 441 |
|
| 442 |
no_proxy = get_proxy('no_proxy') |
| 443 |
|
| 444 |
if no_proxy: |
| 445 |
|
| 446 |
|
| 447 |
no_proxy = no_proxy.split(',') |
| 448 |
netloc = urlparse(url).netloc |
| 449 |
|
| 450 |
for host in no_proxy: |
| 451 |
if netloc.endswith(host) or netloc.split(':')[0].endswith(host): |
| 452 |
|
| 453 |
|
| 454 |
return {} |
| 455 |
|
| 456 |
|
| 457 |
|
| 458 |
proxies = [(key, get_proxy(key + '_proxy')) for key in proxy_keys] |
| 459 |
return dict([(key, val) for (key, val) in proxies if val]) |
| 460 |
|
| 461 |
|
| 462 |
def default_user_agent(): |
| 463 |
"""Return a string representing the default user agent.""" |
| 464 |
_implementation = platform.python_implementation() |
| 465 |
|
| 466 |
if _implementation == 'CPython': |
| 467 |
_implementation_version = platform.python_version() |
| 468 |
elif _implementation == 'PyPy': |
| 469 |
_implementation_version = '%s.%s.%s' % (sys.pypy_version_info.major, |
| 470 |
sys.pypy_version_info.minor, |
| 471 |
sys.pypy_version_info.micro) |
| 472 |
if sys.pypy_version_info.releaselevel != 'final': |
| 473 |
_implementation_version = ''.join([_implementation_version, sys.pypy_version_info.releaselevel]) |
| 474 |
elif _implementation == 'Jython': |
| 475 |
_implementation_version = platform.python_version() |
| 476 |
elif _implementation == 'IronPython': |
| 477 |
_implementation_version = platform.python_version() |
| 478 |
else: |
| 479 |
_implementation_version = 'Unknown' |
| 480 |
|
| 481 |
try: |
| 482 |
p_system = platform.system() |
| 483 |
p_release = platform.release() |
| 484 |
except IOError: |
| 485 |
p_system = 'Unknown' |
| 486 |
p_release = 'Unknown' |
| 487 |
|
| 488 |
return " ".join(['python-requests/%s' % __version__, |
| 489 |
'%s/%s' % (_implementation, _implementation_version), |
| 490 |
'%s/%s' % (p_system, p_release)]) |
| 491 |
|
| 492 |
|
| 493 |
def default_headers(): |
| 494 |
return { |
| 495 |
'User-Agent': default_user_agent(), |
| 496 |
'Accept-Encoding': ', '.join(('gzip', 'deflate', 'compress')), |
| 497 |
'Accept': '*/*' |
| 498 |
} |
| 499 |
|
| 500 |
|
| 501 |
def parse_header_links(value): |
| 502 |
"""Return a dict of parsed link headers proxies. |
| 503 |
|
| 504 |
i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg" |
| 505 |
|
| 506 |
""" |
| 507 |
|
| 508 |
links = [] |
| 509 |
|
| 510 |
replace_chars = " '\"" |
| 511 |
|
| 512 |
for val in value.split(","): |
| 513 |
try: |
| 514 |
url, params = val.split(";", 1) |
| 515 |
except ValueError: |
| 516 |
url, params = val, '' |
| 517 |
|
| 518 |
link = {} |
| 519 |
|
| 520 |
link["url"] = url.strip("<> '\"") |
| 521 |
|
| 522 |
for param in params.split(";"): |
| 523 |
try: |
| 524 |
key, value = param.split("=") |
| 525 |
except ValueError: |
| 526 |
break |
| 527 |
|
| 528 |
link[key.strip(replace_chars)] = value.strip(replace_chars) |
| 529 |
|
| 530 |
links.append(link) |
| 531 |
|
| 532 |
return links |
| 533 |
|
| 534 |
|
| 535 |
|
| 536 |
_null = '\x00'.encode('ascii') |
| 537 |
_null2 = _null * 2 |
| 538 |
_null3 = _null * 3 |
| 539 |
|
| 540 |
|
| 541 |
def guess_json_utf(data): |
| 542 |
|
| 543 |
|
| 544 |
|
| 545 |
sample = data[:4] |
| 546 |
if sample in (codecs.BOM_UTF32_LE, codecs.BOM32_BE): |
| 547 |
return 'utf-32' |
| 548 |
if sample[:3] == codecs.BOM_UTF8: |
| 549 |
return 'utf-8-sig' |
| 550 |
if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE): |
| 551 |
return 'utf-16' |
| 552 |
nullcount = sample.count(_null) |
| 553 |
if nullcount == 0: |
| 554 |
return 'utf-8' |
| 555 |
if nullcount == 2: |
| 556 |
if sample[::2] == _null2: |
| 557 |
return 'utf-16-be' |
| 558 |
if sample[1::2] == _null2: |
| 559 |
return 'utf-16-le' |
| 560 |
|
| 561 |
if nullcount == 3: |
| 562 |
if sample[:3] == _null3: |
| 563 |
return 'utf-32-be' |
| 564 |
if sample[1:] == _null3: |
| 565 |
return 'utf-32-le' |
| 566 |
|
| 567 |
return None |
| 568 |
|
| 569 |
|
| 570 |
def prepend_scheme_if_needed(url, new_scheme): |
| 571 |
'''Given a URL that may or may not have a scheme, prepend the given scheme. |
| 572 |
Does not replace a present scheme with the one provided as an argument.''' |
| 573 |
scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme) |
| 574 |
|
| 575 |
|
| 576 |
|
| 577 |
|
| 578 |
if not netloc: |
| 579 |
netloc, path = path, netloc |
| 580 |
|
| 581 |
return urlunparse((scheme, netloc, path, params, query, fragment)) |
| 582 |
|
| 583 |
|
| 584 |
def get_auth_from_url(url): |
| 585 |
"""Given a url with authentication components, extract them into a tuple of |
| 586 |
username,password.""" |
| 587 |
if url: |
| 588 |
parsed = urlparse(url) |
| 589 |
return (parsed.username, parsed.password) |
| 590 |
else: |
| 591 |
return ('', '') |