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
Provenance
- Commit
ab27027- Tree
59ae619- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
2161d8f
4 files changed+56 added−299 removed
deleted:requests/compat.py.orig-123 removed
1-# -*- coding: utf-8 -*-2-3-"""4-pythoncompat5-"""6-7-8-import sys9-10-# -------11-# Pythons12-# -------13-14-# Syntax sugar.15-_ver = sys.version_info16-17-#: Python 2.x?18-is_py2 = (_ver[0] == 2)19-20-#: Python 3.x?21-is_py3 = (_ver[0] == 3)22-23-#: Python 3.0.x24-is_py30 = (is_py3 and _ver[1] == 0)25-26-#: Python 3.1.x27-is_py31 = (is_py3 and _ver[1] == 1)28-29-#: Python 3.2.x30-is_py32 = (is_py3 and _ver[1] == 2)31-32-#: Python 3.3.x33-is_py33 = (is_py3 and _ver[1] == 3)34-35-#: Python 3.4.x36-is_py34 = (is_py3 and _ver[1] == 4)37-38-#: Python 2.7.x39-is_py27 = (is_py2 and _ver[1] == 7)40-41-#: Python 2.6.x42-is_py26 = (is_py2 and _ver[1] == 6)43-44-#: Python 2.5.x45-is_py25 = (is_py2 and _ver[1] == 5)46-47-#: Python 2.4.x48-is_py24 = (is_py2 and _ver[1] == 4) # I'm assuming this is not by choice.49-50-51-# ---------52-# Platforms53-# ---------54-55-56-# Syntax sugar.57-_ver = sys.version.lower()58-59-is_pypy = ('pypy' in _ver)60-is_jython = ('jython' in _ver)61-is_ironpython = ('iron' in _ver)62-63-# Assume CPython, if nothing else.64-is_cpython = not any((is_pypy, is_jython, is_ironpython))65-66-# Windows-based system.67-is_windows = 'win32' in str(sys.platform).lower()68-69-# Standard Linux 2+ system.70-is_linux = ('linux' in str(sys.platform).lower())71-is_osx = ('darwin' in str(sys.platform).lower())72-is_hpux = ('hpux' in str(sys.platform).lower()) # Complete guess.73-is_solaris = ('solar==' in str(sys.platform).lower()) # Complete guess.74-75-try:76- import simplejson as json77-except ImportError:78- import json79-80-# ---------81-# Specifics82-# ---------83-84-try:85- import cchardet as chardet86-except ImportError:87- from .packages import chardet88-89-90-if 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 OrderedDict98-99- builtin_str = str100- bytes = str101- str = unicode102- basestring = basestring103- numeric_types = (int, long, float)104-105-106-107-elif 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 OrderedDict118-119- 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 lines31 32 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).scheme36 37 def get_type(self):38 return self.type39 339 unmodified linesmodified:requests/defaults.py+2 added-7 removed
28 unmodified lines29 'Accept-Encoding': ', '.join(('gzip', 'deflate', 'compress')),30 'Accept': '*/*'31 }32 33-defaults['verbose'] = None33+# Consumed at the session level, not connection.34 defaults['max_redirects'] = 3035-defaults['pool_connections'] = 1036-defaults['pool_maxsize'] = 1037-defaults['max_retries'] = 038-defaults['keep_alive'] = True39-defaults['encode_uri'] = True35 defaults['trust_env'] = True41-defaults['support_http0.9'] = True36+# defaults['support_http0.9'] = Truemodified:requests/models.py+53 added-168 removed
188 unmodified lines189 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)196 197 149 unmodified lines347 # Update self to reflect the auth changes.348 self.__dict__.update(r.__dict__)349 350 def prepare_cookies(self, cookies):350- #: CookieJar to attach to :class:`Request <Request>`.351+352 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)356 357+ 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_header361+362 def send(self):363 pass364 # return365 255 unmodified lines621 proxies=self.proxies,622 verify=self.verify,623 session=self.session,624 cert=self.cert,619- prefetch=self.prefetch,625+ prefetch=self.prefetch626 )627 628 request.send()629 r = request.response3 unmodified lines633 self.response = r634 self.response.request = self635 636 631-632- def _encode_files(self, files):633- """Build the body for a multipart/form-data request.634-635- 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.638-639- """640- if (not files) or isinstance(self.data, str):641- return None642-643- new_fields = []644- fields = to_key_val_list(self.data)645- files = to_key_val_list(files)646-647- 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)))653-654- 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())))666-667- body, content_type = encode_multipart_formdata(new_fields)668-669- return body, content_type670-671- @property672- def full_url(self):673- """Build the actual URL to use."""674-675- if not self.url:676- raise URLRequired()677-678- url = self.url679-680- # Support for unicode domain names and paths.681- scheme, netloc, path, params, query, fragment = urlparse(url)682-683- if not scheme:684- raise MissingSchema("Invalid URL %r: No schema supplied" % url)685-686- if not scheme in SCHEMAS:687- raise InvalidSchema("Invalid scheme %r" % scheme)688-689- try:690- netloc = netloc.encode('idna').decode('utf-8')691- except UnicodeError:692- raise InvalidURL('URL has an invalid label.')693-694- if not path:695- path = '/'696-697- 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')710-711- 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_params717-718- url = (urlunparse([scheme, netloc, path, params, query, fragment]))719-720- if self.config.get('encode_uri', True):721- url = requote_uri(url)722-723- return url724-725- @property726- def path_url(self):727- """Build the path URL to use."""728-729- url = []730-731- p = urlsplit(self.full_url)732-733- # Proxies use full URLs.734- if p.scheme in self.proxies:735- url_base, frag = urldefrag(self.full_url)736- return url_base737-738-739- path = p.path740- if not path:741- path = '/'742-743- url.append(path)744-745- query = p.query746- if query:747- url.append('?')748- url.append(query)749-750- return ''.join(url)751-637 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 lines736 737 if not self.config.get('keep_alive'):738 self.headers['Connection'] = 'close'739 855- if url.startswith('https') and self.verify:740+ # if url.startswith('https') and self.verify:741 857- cert_loc = None742+ # cert_loc = None743 859- # 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.verify747 863- # 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')751 867- # 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')755 871- if not cert_loc:872- cert_loc = DEFAULT_CA_BUNDLE_PATH756+ # if not cert_loc:757+ # cert_loc = DEFAULT_CA_BUNDLE_PATH758 874- 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.")761 877- 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 = None767 883- 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.cert774 775 if not self.sent or anyway:776 777 # Skip if 'cookie' header is explicitly set.70 unmodified lines848 def prepare(self):849 return deepcopy(self)850 851 852+class 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 = None861 862+968-class Response(object):863+class 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 """869 870 def __init__(self):871+ super(Response, self).__init__()872 873 self._content = False874 self._content_consumed = False875 12 unmodified lines888 889 #: Final URL location of Response.890 self.url = None891 996- #: Resulting :class:`HTTPError` of request, if one occurred.997- self.error = None998-892 #: Encoding to decode with when accessing r.text.893 self.encoding = None894 895 #: A list of :class:`Response <Response>` objects from1 unmodified line897 #: up here. The list is sorted from the oldest to the most recent request.898 self.history = []899 900 #: The :class:`Request <Request>` that created the Response.1008- self.request = None901+ # self.request = None902 903+ self.reason = None904+905 #: A CookieJar of Cookies the server sent back.906 self.cookies = None907 908 #: Dictionary of configurations for this request.165 unmodified lines1074 l[key] = link1075 1076 return l1077 1183- @property1184- def reason(self):1185- """The HTTP Reason for the response."""1186- return self.raw.reason1187-1188- 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."""1080 1191- if self.error:1192- raise self.error1193-1081 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)1082 1198- 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)1085 1086 elif 500 <= self.status_code < 600:1087 http_error_msg = '%s Server Error: %s' % (self.status_code, self.reason)5 unmodified lines