Skip to content
Myr

CHUNKED REQUESTS!

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 4a5b5bc · Browse files · 4 files+121 added−37 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+121 added−37 removed

  • other:+121 added−37 removed

4 files+121 added−37 removed

modified:requests/adapters.py+43 added-13 removed
10 unmodified lines
11import socket1213from .models import Response14from .packages.urllib3.poolmanager import PoolManager, proxy_from_url15from .packages.urllib3.response import HTTPResponse16from .hooks import dispatch_hook17from .compat import urlparse, basestring, urldefrag18from .utils import (DEFAULT_CA_BUNDLE_PATH, get_encoding_from_headers,19 prepend_scheme_if_needed)
134 unmodified lines
154155 conn = self.get_connection(request.url, proxies)156157 self.cert_verify(conn, request.url, verify, cert)157158 url = self.request_url(request, proxies)159160 chunked = not (request.body is None or 'Content-Length' in request.headers)161162 try:163 if not chunked:164 resp = conn.urlopen(165 method=request.method,166 url=url,167 body=request.body,168 headers=request.headers,169 redirect=False,170 assert_same_host=False,171 preload_content=False,172 decode_content=False,173 retries=self.max_retries,174 timeout=timeout175 )176177 # Send the request.162 resp = conn.urlopen(163 method=request.method,164 url=url,165 body=request.body,166 headers=request.headers,167 redirect=False,168 assert_same_host=False,169 preload_content=False,170 decode_content=False,171 retries=self.max_retries,172 timeout=timeout,173 )178 else:179 if hasattr(conn, 'proxy_pool'):180 conn = conn.proxy_pool181182 low_conn = conn._get_conn(timeout=timeout)183 low_conn.putrequest(request.method, url, skip_accept_encoding=True)184185 for header, value in request.headers.items():186 low_conn.putheader(header, value)187188 low_conn.endheaders()189190 for i in request.body:191 low_conn.send(hex(len(i))[2:].encode('utf-8'))192 low_conn.send(b'\r\n')193 low_conn.send(i)194 low_conn.send(b'\r\n')195 low_conn.send(b'0\r\n\r\n')196197 r = low_conn.getresponse()198 resp = HTTPResponse.from_httplib(r,199 pool=conn,200 connection=low_conn,201 preload_content=False,202 decode_content=False203 )204205 except socket.error as sockerr:206 raise ConnectionError(sockerr)207208 except MaxRetryError as e:
16 unmodified lines
modified:requests/models.py+49 added-24 removed
20 unmodified lines
21from .exceptions import HTTPError, RequestException, MissingSchema, InvalidURL22from .utils import (23 stream_untransfer, guess_filename, requote_uri,24 stream_decode_response_unicode, to_key_val_list, parse_header_links,25 iter_slices, guess_json_utf)25 iter_slices, guess_json_utf, super_len)26from .compat import (27 cookielib, urlparse, urlunparse, urlsplit, urlencode, str, bytes, StringIO,28 is_py2, chardet, json, builtin_str, basestring)29
290 unmodified lines
320321 def prepare_body(self, data, files):322 """Prepares the given HTTP body data."""323324 # If a generator is provided, error out.325 if isinstance(data, type(_ for _ in [])):326 raise NotImplementedError('Generator bodies are not supported yet.')324 # Check if file, fo, generator, iterator.325 # If not, run through normal process.326327 # Nottin' on you.328 body = None329 content_type = None330 length = None331 is_stream = False332332 # Multi-part file uploads.333 if files:334 (body, content_type) = self._encode_files(files, data)335 else:336 if data:333 is_stream = all([334 hasattr(data, '__iter__'),335 not isinstance(data, basestring),336 not isinstance(data, dict)337 ])338338 body = self._encode_params(data)339 if isinstance(data, str) or isinstance(data, builtin_str) or hasattr(data, 'read'):340 content_type = None341 else:342 content_type = 'application/x-www-form-urlencoded'339 try:340 length = super_len(data)341 except (TypeError, AttributeError):342 length = False343344 self.headers['Content-Length'] = '0'345 if hasattr(body, 'seek') and hasattr(body, 'tell'):346 body.seek(0, 2)347 self.headers['Content-Length'] = str(body.tell())348 body.seek(0, 0)349 elif body is not None:350 self.headers['Content-Length'] = str(len(body))344 if is_stream:345 body = data346352 # Add content-type if it wasn't explicitly provided.353 if (content_type) and (not 'content-type' in self.headers):354 self.headers['Content-Type'] = content_type347 if files:348 raise NotImplementedError('Streamed bodies and files are mutually exclusive.')349350 if length:351 self.headers['Content-Length'] = length352 else:353 self.headers['Transfer-Encoding'] = 'chunked'354 # Check if file, fo, generator, iterator.355 # If not, run through normal process.356357 else:358 # Multi-part file uploads.359 if files:360 (body, content_type) = self._encode_files(files, data)361 else:362 if data:363 body = self._encode_params(data)364 if isinstance(data, str) or isinstance(data, builtin_str) or hasattr(data, 'read'):365 content_type = None366 else:367 content_type = 'application/x-www-form-urlencoded'368369 self.headers['Content-Length'] = '0'370 if hasattr(body, 'seek') and hasattr(body, 'tell'):371 body.seek(0, 2)372 self.headers['Content-Length'] = str(body.tell())373 body.seek(0, 0)374 elif body is not None:375 self.headers['Content-Length'] = str(len(body))376377 # Add content-type if it wasn't explicitly provided.378 if (content_type) and (not 'content-type' in self.headers):379 self.headers['Content-Type'] = content_type380381 self.body = body382383 def prepare_auth(self, auth):384 """Prepares the given HTTP auth data."""
248 unmodified lines
modified:requests/structures.py+22 added
6 unmodified lines
7Data structures that power Requests.89"""1011import os12from itertools import islice1314class IteratorProxy(object):15 """docstring for IteratorProxy"""16 def __init__(self, i):17 self.i = i18 # self.i = chain.from_iterable(i)1920 def __iter__(self):21 return self.i2223 def __len__(self):24 if hasattr(self.i, '__len__'):25 return len(self.i)26 if hasattr(self.i, 'len'):27 return self.i.len28 if hasattr(self.i, 'fileno'):29 return os.fstat(self.i.fileno()).st_size3031 def read(self, n):32 return "".join(islice(self.i, None, n))3334class CaseInsensitiveDict(dict):35 """Case-insensitive Dictionary3637 For example, ``headers['content-encoding']`` will return the
52 unmodified lines
modified:requests/utils.py+7 added
38 unmodified lines
39 d = d.items()4041 return d4243def super_len(o):44 if hasattr(o, '__len__'):45 return len(o)46 if hasattr(o, 'len'):47 return o.len48 if hasattr(o, 'fileno'):49 return os.fstat(o.fileno()).st_size5051def get_netrc_auth(url):52 """Returns the Requests tuple auth for a given url from netrc."""53
531 unmodified lines