Skip to content
Myr

cookies

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Kenneth Reitz · committed by Kenneth Reitz · parent 2161d8f · Browse files · 4 files+56 added−299 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+56 added−299 removed

  • other:+56 added−299 removed

4 files+56 added−299 removed

deleted:requests/compat.py.orig-123 removed
1# -*- coding: utf-8 -*-23"""4pythoncompat5"""678import sys910# -------11# Pythons12# -------1314# Syntax sugar.15_ver = sys.version_info1617#: Python 2.x?18is_py2 = (_ver[0] == 2)1920#: Python 3.x?21is_py3 = (_ver[0] == 3)2223#: Python 3.0.x24is_py30 = (is_py3 and _ver[1] == 0)2526#: Python 3.1.x27is_py31 = (is_py3 and _ver[1] == 1)2829#: Python 3.2.x30is_py32 = (is_py3 and _ver[1] == 2)3132#: Python 3.3.x33is_py33 = (is_py3 and _ver[1] == 3)3435#: Python 3.4.x36is_py34 = (is_py3 and _ver[1] == 4)3738#: Python 2.7.x39is_py27 = (is_py2 and _ver[1] == 7)4041#: Python 2.6.x42is_py26 = (is_py2 and _ver[1] == 6)4344#: Python 2.5.x45is_py25 = (is_py2 and _ver[1] == 5)4647#: Python 2.4.x48is_py24 = (is_py2 and _ver[1] == 4) # I'm assuming this is not by choice.495051# ---------52# Platforms53# ---------545556# Syntax sugar.57_ver = sys.version.lower()5859is_pypy = ('pypy' in _ver)60is_jython = ('jython' in _ver)61is_ironpython = ('iron' in _ver)6263# Assume CPython, if nothing else.64is_cpython = not any((is_pypy, is_jython, is_ironpython))6566# Windows-based system.67is_windows = 'win32' in str(sys.platform).lower()6869# Standard Linux 2+ system.70is_linux = ('linux' in str(sys.platform).lower())71is_osx = ('darwin' in str(sys.platform).lower())72is_hpux = ('hpux' in str(sys.platform).lower()) # Complete guess.73is_solaris = ('solar==' in str(sys.platform).lower()) # Complete guess.7475try:76 import simplejson as json77except ImportError:78 import json7980# ---------81# Specifics82# ---------8384try:85 import cchardet as chardet86except ImportError:87 from .packages import chardet888990if is_py2:91 from urllib import quote, unquote, quote_plus, unquote_plus, urlencode92 from urlparse import urlparse, urlunparse, urljoin, urlsplit, urldefrag93 from urllib2 import parse_http_list94 import cookielib95 from Cookie import Morsel96 from StringIO import StringIO97 from .packages.urllib3.packages.ordered_dict import OrderedDict9899 builtin_str = str100 bytes = str101 str = unicode102 basestring = basestring103 numeric_types = (int, long, float)104105106107elif is_py3:108 from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote, quote_plus, unquote_plus, urldefrag109 from urllib.request import parse_http_list110 from http import cookiejar as cookielib111 from http.cookies import Morsel112 from io import StringIO113<<<<<<< HEAD114=======115 from .packages import chardet116>>>>>>> 8f86ff633a2646442f2d8976046b5c0025e772c1117 from collections import OrderedDict118119 builtin_str = str120 str = str121 bytes = bytes122 basestring = (str, bytes)123 numeric_types = (int, float)
modified:requests/cookies.py+1 added-1 removed
30 unmodified lines
3132 def __init__(self, request):33 self._r = request34 self._new_headers = {}35 self.type = urlparse(self._r.full_url).scheme35 self.type = urlparse(self._r.url).scheme3637 def get_type(self):38 return self.type39
339 unmodified lines
modified:requests/defaults.py+2 added-7 removed
28 unmodified lines
29 'Accept-Encoding': ', '.join(('gzip', 'deflate', 'compress')),30 'Accept': '*/*'31}3233defaults['verbose'] = None33# Consumed at the session level, not connection.34defaults['max_redirects'] = 3035defaults['pool_connections'] = 1036defaults['pool_maxsize'] = 1037defaults['max_retries'] = 038defaults['keep_alive'] = True39defaults['encode_uri'] = True35defaults['trust_env'] = True41defaults['support_http0.9'] = True36# defaults['support_http0.9'] = True
modified:requests/models.py+53 added-168 removed
188 unmodified lines
189 p = PreparedRequest()190 p.prepare_method(self.method)191 p.prepare_url(self.url, self.params)192 p.prepare_headers(self.headers)193 p.prepare_cookies(self.cookies)194 p.prepare_auth(self.auth)195 p.prepare_body(self.data, self.files)196197
149 unmodified lines
347 # Update self to reflect the auth changes.348 self.__dict__.update(r.__dict__)349350 def prepare_cookies(self, cookies):350 #: CookieJar to attach to :class:`Request <Request>`.351352 if isinstance(cookies, cookielib.CookieJar):352 self.cookies = cookies353 cookies = cookies354 else:354 self.cookies = cookiejar_from_dict(cookies)355 cookies = cookiejar_from_dict(cookies)356357 if 'cookie' not in self.headers:358 cookie_header = get_cookie_header(cookies, self)359 if cookie_header is not None:360 self.headers['Cookie'] = cookie_header361362 def send(self):363 pass364 # return365
255 unmodified lines
621 proxies=self.proxies,622 verify=self.verify,623 session=self.session,624 cert=self.cert,619 prefetch=self.prefetch,625 prefetch=self.prefetch626 )627628 request.send()629 r = request.response
3 unmodified lines
633 self.response = r634 self.response.request = self635636631632 def _encode_files(self, files):633 """Build the body for a multipart/form-data request.634635 Will successfully encode files when passed as a dict or a list of636 2-tuples. Order is retained if data is a list of 2-tuples but abritrary637 if parameters are supplied as a dict.638639 """640 if (not files) or isinstance(self.data, str):641 return None642643 new_fields = []644 fields = to_key_val_list(self.data)645 files = to_key_val_list(files)646647 for field, val in fields:648 if isinstance(val, list):649 for v in val:650 new_fields.append((field, builtin_str(v)))651 else:652 new_fields.append((field, builtin_str(val)))653654 for (k, v) in files:655 # support for explicit filename656 if isinstance(v, (tuple, list)):657 fn, fp = v658 else:659 fn = guess_filename(v) or k660 fp = v661 if isinstance(fp, str):662 fp = StringIO(fp)663 if isinstance(fp, bytes):664 fp = BytesIO(fp)665 new_fields.append((k, (fn, fp.read())))666667 body, content_type = encode_multipart_formdata(new_fields)668669 return body, content_type670671 @property672 def full_url(self):673 """Build the actual URL to use."""674675 if not self.url:676 raise URLRequired()677678 url = self.url679680 # Support for unicode domain names and paths.681 scheme, netloc, path, params, query, fragment = urlparse(url)682683 if not scheme:684 raise MissingSchema("Invalid URL %r: No schema supplied" % url)685686 if not scheme in SCHEMAS:687 raise InvalidSchema("Invalid scheme %r" % scheme)688689 try:690 netloc = netloc.encode('idna').decode('utf-8')691 except UnicodeError:692 raise InvalidURL('URL has an invalid label.')693694 if not path:695 path = '/'696697 if is_py2:698 if isinstance(scheme, str):699 scheme = scheme.encode('utf-8')700 if isinstance(netloc, str):701 netloc = netloc.encode('utf-8')702 if isinstance(path, str):703 path = path.encode('utf-8')704 if isinstance(params, str):705 params = params.encode('utf-8')706 if isinstance(query, str):707 query = query.encode('utf-8')708 if isinstance(fragment, str):709 fragment = fragment.encode('utf-8')710711 enc_params = self._encode_params(self.params)712 if enc_params:713 if query:714 query = '%s&%s' % (query, enc_params)715 else:716 query = enc_params717718 url = (urlunparse([scheme, netloc, path, params, query, fragment]))719720 if self.config.get('encode_uri', True):721 url = requote_uri(url)722723 return url724725 @property726 def path_url(self):727 """Build the path URL to use."""728729 url = []730731 p = urlsplit(self.full_url)732733 # Proxies use full URLs.734 if p.scheme in self.proxies:735 url_base, frag = urldefrag(self.full_url)736 return url_base737738739 path = p.path740 if not path:741 path = '/'742743 url.append(path)744745 query = p.query746 if query:747 url.append('?')748 url.append(query)749750 return ''.join(url)751637 def register_hook(self, event, hook):638 """Properly register a hook."""639 if isinstance(hook, collections.Callable):640 self.hooks[event].append(hook)
95 unmodified lines
736737 if not self.config.get('keep_alive'):738 self.headers['Connection'] = 'close'739855 if url.startswith('https') and self.verify:740 # if url.startswith('https') and self.verify:741857 cert_loc = None742 # cert_loc = None743859 # Allow self-specified cert location.860 if self.verify is not True:861 cert_loc = self.verify744 # # Allow self-specified cert location.745 # if self.verify is not True:746 # cert_loc = self.verify747863 # Look for configuration.864 if not cert_loc and self.config.get('trust_env'):865 cert_loc = os.environ.get('REQUESTS_CA_BUNDLE')748 # # Look for configuration.749 # if not cert_loc and self.config.get('trust_env'):750 # cert_loc = os.environ.get('REQUESTS_CA_BUNDLE')751867 # Curl compatibility.868 if not cert_loc and self.config.get('trust_env'):869 cert_loc = os.environ.get('CURL_CA_BUNDLE')752 # # Curl compatibility.753 # if not cert_loc and self.config.get('trust_env'):754 # cert_loc = os.environ.get('CURL_CA_BUNDLE')755871 if not cert_loc:872 cert_loc = DEFAULT_CA_BUNDLE_PATH756 # if not cert_loc:757 # cert_loc = DEFAULT_CA_BUNDLE_PATH758874 if not cert_loc:875 raise Exception("Could not find a suitable SSL CA certificate bundle.")759 # if not cert_loc:760 # raise Exception("Could not find a suitable SSL CA certificate bundle.")761877 conn.cert_reqs = 'CERT_REQUIRED'878 conn.ca_certs = cert_loc879 else:880 conn.cert_reqs = 'CERT_NONE'881 conn.ca_certs = None762 # conn.cert_reqs = 'CERT_REQUIRED'763 # conn.ca_certs = cert_loc764 # else:765 # conn.cert_reqs = 'CERT_NONE'766 # conn.ca_certs = None767883 if self.cert:884 if len(self.cert) == 2:885 conn.cert_file = self.cert[0]886 conn.key_file = self.cert[1]887 else:888 conn.cert_file = self.cert768 # if self.cert:769 # if len(self.cert) == 2:770 # conn.cert_file = self.cert[0]771 # conn.key_file = self.cert[1]772 # else:773 # conn.cert_file = self.cert774775 if not self.sent or anyway:776777 # Skip if 'cookie' header is explicitly set.
70 unmodified lines
848 def prepare(self):849 return deepcopy(self)850851852class BaseResponse(object):853 """The basic Respone"""854 def __init__(self):855 self.url = None856 self.status_code = None857 self.reason = None858 self.headers = None859 self.data = None860 self.body = None861862968class Response(object):863class Response(BaseResponse):864 """The core :class:`Response <Response>` object. All865 :class:`Request <Request>` objects contain a866 :class:`response <Response>` attribute, which is an instance867 of this class.868 """869870 def __init__(self):871 super(Response, self).__init__()872873 self._content = False874 self._content_consumed = False875
12 unmodified lines
888889 #: Final URL location of Response.890 self.url = None891996 #: Resulting :class:`HTTPError` of request, if one occurred.997 self.error = None998892 #: Encoding to decode with when accessing r.text.893 self.encoding = None894895 #: A list of :class:`Response <Response>` objects from
1 unmodified line
897 #: up here. The list is sorted from the oldest to the most recent request.898 self.history = []899900 #: The :class:`Request <Request>` that created the Response.1008 self.request = None901 # self.request = None902903 self.reason = None904905 #: A CookieJar of Cookies the server sent back.906 self.cookies = None907908 #: Dictionary of configurations for this request.
165 unmodified lines
1074 l[key] = link10751076 return l10771183 @property1184 def reason(self):1185 """The HTTP Reason for the response."""1186 return self.raw.reason11871188 def raise_for_status(self, allow_redirects=True):1078 def raise_for_status(self):1079 """Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred."""10801191 if self.error:1192 raise self.error11931081 http_error_msg = ''1195 if 300 <= self.status_code < 400 and not allow_redirects:1196 http_error_msg = '%s Redirection: %s' % (self.status_code, self.reason)10821198 elif 400 <= self.status_code < 500:1083 if 400 <= self.status_code < 500:1084 http_error_msg = '%s Client Error: %s' % (self.status_code, self.reason)10851086 elif 500 <= self.status_code < 600:1087 http_error_msg = '%s Server Error: %s' % (self.status_code, self.reason)
5 unmodified lines