~ubuntu-branches/ubuntu/utopic/requests/utopic

« back to all changes in this revision

Viewing changes to requests/utils.py

  • Committer: Package Import Robot
  • Author(s): Daniele Tricoli
  • Date: 2013-10-18 19:20:21 UTC
  • mfrom: (1.1.13)
  • Revision ID: package-import@ubuntu.com-20131018192021-hzbd8k13wgx2z8am
Tags: 2.0.0-1
* New upstream release (Closes: #725784)
* Switched to pybuild
* debian/clean
  - Switched to debian/clean for cleaning instead of using debian/rules
* debian/control
  - Bumped python(3)-urllib3 to (>=1.7.1)
* debian/copyright
  - Updated copyright year
* debian/patches/02_use-system-chardet-and-urllib3.patches
  - Refreshed
* debian/watch
  - Switched download URL to https

Show diffs side-by-side

added added

removed removed

Lines of Context:
21
21
from . import __version__
22
22
from . import certs
23
23
from .compat import parse_http_list as _parse_list_header
24
 
from .compat import quote, urlparse, bytes, str, OrderedDict, urlunparse
 
24
from .compat import (quote, urlparse, bytes, str, OrderedDict, urlunparse,
 
25
                     is_py2, is_py3, builtin_str, getproxies, proxy_bypass)
25
26
from .cookies import RequestsCookieJar, cookiejar_from_dict
26
27
from .structures import CaseInsensitiveDict
 
28
from .exceptions import MissingSchema, InvalidURL
27
29
 
28
30
_hush_pyflakes = (RequestsCookieJar,)
29
31
 
264
266
    """
265
267
 
266
268
    charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)
 
269
    pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I)
 
270
    xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')
267
271
 
268
 
    return charset_re.findall(content)
 
272
    return (charset_re.findall(content) +
 
273
            pragma_re.findall(content) +
 
274
            xml_re.findall(content))
269
275
 
270
276
 
271
277
def get_encoding_from_headers(headers):
301
307
        rv = decoder.decode(chunk)
302
308
        if rv:
303
309
            yield rv
304
 
    rv = decoder.decode('', final=True)
 
310
    rv = decoder.decode(b'', final=True)
305
311
    if rv:
306
312
        yield rv
307
313
 
361
367
    for i in range(1, len(parts)):
362
368
        h = parts[i][0:2]
363
369
        if len(h) == 2 and h.isalnum():
364
 
            c = chr(int(h, 16))
 
370
            try:
 
371
                c = chr(int(h, 16))
 
372
            except ValueError:
 
373
                raise InvalidURL("Invalid percent-escape sequence: '%s'" % h)
 
374
 
365
375
            if c in UNRESERVED_SET:
366
376
                parts[i] = c + parts[i][2:]
367
377
            else:
386
396
def get_environ_proxies(url):
387
397
    """Return a dict of environment proxies."""
388
398
 
389
 
    proxy_keys = [
390
 
        'all',
391
 
        'http',
392
 
        'https',
393
 
        'ftp',
394
 
        'socks'
395
 
    ]
396
 
 
397
399
    get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())
398
400
 
399
401
    # First check whether no_proxy is defined. If it is, check that the URL
400
402
    # we're getting isn't in the no_proxy list.
401
403
    no_proxy = get_proxy('no_proxy')
 
404
    netloc = urlparse(url).netloc
402
405
 
403
406
    if no_proxy:
404
407
        # We need to check whether we match here. We need to see if we match
405
408
        # the end of the netloc, both with and without the port.
406
 
        no_proxy = no_proxy.split(',')
407
 
        netloc = urlparse(url).netloc
 
409
        no_proxy = no_proxy.replace(' ', '').split(',')
408
410
 
409
411
        for host in no_proxy:
410
412
            if netloc.endswith(host) or netloc.split(':')[0].endswith(host):
412
414
                # to apply the proxies on this URL.
413
415
                return {}
414
416
 
 
417
    # If the system proxy settings indicate that this URL should be bypassed,
 
418
    # don't proxy.
 
419
    if proxy_bypass(netloc):
 
420
        return {}
 
421
 
415
422
    # If we get here, we either didn't have no_proxy set or we're not going
416
 
    # anywhere that no_proxy applies to.
417
 
    proxies = [(key, get_proxy(key + '_proxy')) for key in proxy_keys]
418
 
    return dict([(key, val) for (key, val) in proxies if val])
 
423
    # anywhere that no_proxy applies to, and the system settings don't require
 
424
    # bypassing the proxy for the current URL.
 
425
    return getproxies()
419
426
 
420
427
 
421
428
def default_user_agent():
526
533
    return None
527
534
 
528
535
 
529
 
def prepend_scheme_if_needed(url, new_scheme):
530
 
    '''Given a URL that may or may not have a scheme, prepend the given scheme.
531
 
    Does not replace a present scheme with the one provided as an argument.'''
532
 
    scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme)
533
 
 
534
 
    # urlparse is a finicky beast, and sometimes decides that there isn't a
535
 
    # netloc present. Assume that it's being over-cautious, and switch netloc
536
 
    # and path if urlparse decided there was no netloc.
537
 
    if not netloc:
538
 
        netloc, path = path, netloc
539
 
 
540
 
    return urlunparse((scheme, netloc, path, params, query, fragment))
 
536
def except_on_missing_scheme(url):
 
537
    """Given a URL, raise a MissingSchema exception if the scheme is missing.
 
538
    """
 
539
    scheme, netloc, path, params, query, fragment = urlparse(url)
 
540
 
 
541
    if not scheme:
 
542
        raise MissingSchema('Proxy URLs must have explicit schemes.')
541
543
 
542
544
 
543
545
def get_auth_from_url(url):
548
550
        return (parsed.username, parsed.password)
549
551
    else:
550
552
        return ('', '')
 
553
 
 
554
 
 
555
def to_native_string(string, encoding='ascii'):
 
556
    """
 
557
    Given a string object, regardless of type, returns a representation of that
 
558
    string in the native string type, encoding and decoding where necessary.
 
559
    This assumes ASCII unless told otherwise.
 
560
    """
 
561
    out = None
 
562
 
 
563
    if isinstance(string, builtin_str):
 
564
        out = string
 
565
    else:
 
566
        if is_py2:
 
567
            out = string.encode(encoding)
 
568
        else:
 
569
            out = string.decode(encoding)
 
570
 
 
571
    return out