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
Provenance
- Commit
ef8563a- Tree
433bf3f- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
4a5b5bc
4 files changed+121 added−37 removed
modified:requests/adapters.py+43 added-13 removed
10 unmodified lines11 import socket12 13 from .models import Response14 from .packages.urllib3.poolmanager import PoolManager, proxy_from_url15+from .packages.urllib3.response import HTTPResponse16 from .hooks import dispatch_hook17 from .compat import urlparse, basestring, urldefrag18 from .utils import (DEFAULT_CA_BUNDLE_PATH, get_encoding_from_headers,19 prepend_scheme_if_needed)134 unmodified lines154 155 conn = self.get_connection(request.url, proxies)156 157 self.cert_verify(conn, request.url, verify, cert)157-158 url = self.request_url(request, proxies)159 160+ chunked = not (request.body is None or 'Content-Length' in request.headers)161+162 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+ )176+177 # 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_pool181 182+ low_conn = conn._get_conn(timeout=timeout)183+ low_conn.putrequest(request.method, url, skip_accept_encoding=True)184+185+ for header, value in request.headers.items():186+ low_conn.putheader(header, value)187+188+ low_conn.endheaders()189+190+ 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')196+197+ 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+ )204+205 except socket.error as sockerr:206 raise ConnectionError(sockerr)207 208 except MaxRetryError as e:16 unmodified linesmodified:requests/models.py+49 added-24 removed
20 unmodified lines21 from .exceptions import HTTPError, RequestException, MissingSchema, InvalidURL22 from .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)26 from .compat import (27 cookielib, urlparse, urlunparse, urlsplit, urlencode, str, bytes, StringIO,28 is_py2, chardet, json, builtin_str, basestring)29 290 unmodified lines320 321 def prepare_body(self, data, files):322 """Prepares the given HTTP body data."""323 324- # 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.326 327 # Nottin' on you.328 body = None329 content_type = None330+ length = None331+ is_stream = False332 332- # 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+ ])338 338- 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 = False343 344- 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 = data346 352- # 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.')349 350+ 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.356+357+ 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'368+369+ 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))376+377+ # 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_type380+381 self.body = body382 383 def prepare_auth(self, auth):384 """Prepares the given HTTP auth data."""248 unmodified linesmodified:requests/structures.py+22 added
6 unmodified lines7 Data structures that power Requests.8 9 """10 11+import os12+from itertools import islice13 14+class IteratorProxy(object):15+ """docstring for IteratorProxy"""16+ def __init__(self, i):17+ self.i = i18+ # self.i = chain.from_iterable(i)19+20+ def __iter__(self):21+ return self.i22+23+ 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_size30+31+ def read(self, n):32+ return "".join(islice(self.i, None, n))33+34 class CaseInsensitiveDict(dict):35 """Case-insensitive Dictionary36 37 For example, ``headers['content-encoding']`` will return the52 unmodified linesmodified:requests/utils.py+7 added
38 unmodified lines39 d = d.items()40 41 return d42 43+def 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_size50 51 def get_netrc_auth(url):52 """Returns the Requests tuple auth for a given url from netrc."""53 531 unmodified lines