Skip to content
Myr

Merge pull request #202 from kennethreitz/feature/content-stream

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

Content Streaming

authored by Kenneth Reitz · committed by Kenneth Reitz · parents b14fa07, daf7aeb · Browse files · 14 files+354 added−158 removed
This commit

State

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

Diff stats

14 files+354 added−158 removed

  • other:+354 added−158 removed

14 files+354 added−158 removed

modified:docs/community/faq.rst+1 added
8 unmodified lines
9-------------1011Requests automatically decompresses gzip-encoded responses, and does12its best to decodes response content to unicode when possible.13it's best to decodes response content to unicode when possible.1415You can get direct access to the raw response (and even the socket),16if needed as well.17
67 unmodified lines
modified:docs/user/install.rst+1 added-1 removed
73 unmodified lines
74 $ apt-get install libevent-dev7576Once you have ``libevent``, you can install ``gevent`` with ``pip``::7778 $ pip install gevent78 $ pip install gevent
modified:docs/user/intro.rst-2 removed
45 unmodified lines
46 Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.4748 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.495051
modified:docs/api.rst+15 added-3 removed
29 unmodified lines
3031.. autoclass:: Response32 :inherited-members:3334Async35-----3637.. module:: requests.async383940.. autofunction:: map41.. autofunction:: request42.. autofunction:: head43.. autofunction:: get44.. autofunction:: post45.. autofunction:: put46.. autofunction:: patch47.. autofunction:: delete48495051Utilities52---------5354These functions are used internally, but may be useful outside of
7 unmodified lines
62.. autofunction:: dict_from_cookiejar63.. autofunction:: cookiejar_from_dict64.. autofunction:: add_dict_to_cookiejar6551Curl52~~~~53.. autofunction:: curl_from_request6667Encodings68~~~~~~~~~69
36 unmodified lines
modified:requests/api.py+22 added-55 removed
13 unmodified lines
14import config15from .models import Request, Response, AuthObject16from .status_codes import codes17from .hooks import dispatch_hook18from .utils import cookiejar_from_dict18from .utils import cookiejar_from_dict, header_expand192021__all__ = ('request', 'get', 'head', 'post', 'patch', 'put', 'delete')2223def request(method, url,24 params=None, data=None, headers=None, cookies=None, files=None, auth=None,25 timeout=None, allow_redirects=False, proxies=None, hooks=None, return_response=True):2627 """Constructs and sends a :class:`Request <models.Request>`.28 Returns :class:`Response <models.Response>` object.27 """Constructs and sends a :class:`Request <Request>`.28 Returns :class:`Response <Response>` object.2930 :param method: method for the new :class:`Request` object.31 :param url: URL for the new :class:`Request` object.32 :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
4 unmodified lines
37 :param auth: (optional) AuthObject to enable Basic HTTP Auth.38 :param timeout: (optional) Float describing the timeout of the request.39 :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.40 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.41 :param return_response: (optional) If False, an un-sent Request object will returned.42 """4344 method = str(method).upper()4546 if cookies is None:47 cookies = {}4849 cookies = cookiejar_from_dict(cookies)5051 # Expand header values52 if headers:53 for k, v in headers.items() or {}:54 headers[k] = header_expand(v)5556 args = dict(57 method = method,58 url = url,59 data = data,
36 unmodified lines
9697 """Sends a GET request. Returns :class:`Response` object.9899 :param url: URL for the new :class:`Request` object.92 :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.93 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.94 :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.95 :param auth: (optional) AuthObject to enable Basic HTTP Auth.96 :param timeout: (optional) Float describing the timeout of the request.97 :param allow_redirects: (optional) Boolean. Set to False to disable redirect following.98 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.100 :param **kwargs: Optional arguments that ``request`` takes.101 """102103104 kwargs.setdefault('allow_redirects', True)105 return request('GET', url, **kwargs)106107108def head(url, **kwargs):106109 """Sends a HEAD request. Returns :class:`Response` object.110111 :param url: URL for the new :class:`Request` object.110 :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.111 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.112 :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.113 :param auth: (optional) AuthObject to enable Basic HTTP Auth.114 :param timeout: (optional) Float describing the timeout of the request.115 :param allow_redirects: (optional) Boolean. Set to False to disable redirect following.116 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.112 :param **kwargs: Optional arguments that ``request`` takes.113 """114115 kwargs.setdefault('allow_redirects', True)116 return request('HEAD', url, **kwargs)117118119def post(url, data='', **kwargs):124120 """Sends a POST request. Returns :class:`Response` object.121122 :param url: URL for the new :class:`Request` object.123 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.129 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.130 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.131 :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.132 :param auth: (optional) AuthObject to enable Basic HTTP Auth.133 :param timeout: (optional) Float describing the timeout of the request.134 :param allow_redirects: (optional) Boolean. Set to True if redirect following is allowed.135 :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.136 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.124 :param **kwargs: Optional arguments that ``request`` takes.125 """126139 return request('POST', url, data=data, **kwargs)127 return request('post', url, data=data, **kwargs)128129130def put(url, data='', **kwargs):131 """Sends a PUT request. Returns :class:`Response` object.132133 :param url: URL for the new :class:`Request` object.134 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.147 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.148 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.149 :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.150 :param auth: (optional) AuthObject to enable Basic HTTP Auth.151 :param timeout: (optional) Float describing the timeout of the request.152 :param allow_redirects: (optional) Boolean. Set to True if redirect following is allowed.153 :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.154 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.135 :param **kwargs: Optional arguments that ``request`` takes.136 """137157 return request('PUT', url, data=data, **kwargs)138 return request('put', url, data=data, **kwargs)139140141def patch(url, data='', **kwargs):142 """Sends a PATCH request. Returns :class:`Response` object.143144 :param url: URL for the new :class:`Request` object.145 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.165 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.166 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.167 :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.168 :param auth: (optional) AuthObject to enable Basic HTTP Auth.169 :param timeout: (optional) Float describing the timeout of the request.170 :param allow_redirects: (optional) Boolean. Set to True if redirect following is allowed.171 :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.172 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.146 :param **kwargs: Optional arguments that ``request`` takes.147 """148175 return request('PATCH', url, **kwargs)149 return request('patch', url, **kwargs)150151152def delete(url, **kwargs):179153 """Sends a DELETE request. Returns :class:`Response` object.154155 :param url: URL for the new :class:`Request` object.183 :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.184 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.185 :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.186 :param auth: (optional) AuthObject to enable Basic HTTP Auth.187 :param timeout: (optional) Float describing the timeout of the request.188 :param allow_redirects: (optional) Boolean. Set to True if redirect following is allowed.189 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.156 :param **kwargs: Optional arguments that ``request`` takes.157 """158192 return request('DELETE', url, **kwargs)159 return request('delete', url, **kwargs)
modified:requests/config.py+1 added
60 unmodified lines
61settings.proxies = None62settings.verbose = None63settings.timeout = None64settings.max_redirects = 3065settings.decode_unicode = True6667#: Use socket.setdefaulttimeout() as fallback?68settings.timeout_fallback = True
modified:requests/core.py+4 added-2 removed
17 unmodified lines
18__license__ = 'ISC'19__copyright__ = 'Copyright 2011 Kenneth Reitz'202122from models import HTTPError22from models import HTTPError, Request, Response23from api import *24from exceptions import *25from sessions import session26from status_codes import codes27from config import settings27from config import settings2829import utils
modified:requests/models.py+102 added-47 removed
7 unmodified lines
89import urllib10import urllib211import socket12import codecs13import zlib141516from urllib2 import HTTPError17from urlparse import urlparse, urlunparse, urljoin18from datetime import datetime19
1 unmodified line
21from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPForcedBasicAuthHandler, HTTPDigestAuthHandler, HTTPRedirectHandler22from .structures import CaseInsensitiveDict23from .packages.poster.encode import multipart_encode24from .packages.poster.streaminghttp import register_openers, get_handlers23from .utils import dict_from_cookiejar24from .exceptions import RequestException, AuthenticationError, Timeout, URLRequired, InvalidMethod, TooManyRedirects25from .utils import dict_from_cookiejar, get_unicode_from_response, stream_decode_response_unicode, decode_gzip, stream_decode_gzip26from .status_codes import codes27from .exceptions import RequestException, AuthenticationError, Timeout, URLRequired, InvalidMethod, TooManyRedirects282930REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)31323334class Request(object):33 """The :class:`Request <models.Request>` object. It carries out all functionality of35 """The :class:`Request <Request>` object. It carries out all functionality of36 Requests. Recommended interface is with the Requests functions.37 """3839 def __init__(self,
7 unmodified lines
4748 #: Request URL.49 self.url = url5049 #: Dictonary of HTTP Headers to attach to the :class:`Request <models.Request>`.51 #: Dictonary of HTTP Headers to attach to the :class:`Request <Request>`.52 self.headers = headers5354 #: Dictionary of files to multipart upload (``{filename: content}``).55 self.files = files5655 #: HTTP Method to use. Available: GET, HEAD, PUT, POST, DELETE.57 #: HTTP Method to use.58 self.method = method5960 #: Dictionary or byte of request body data to attach to the59 #: :class:`Request <models.Request>`.61 #: :class:`Request <Request>`.62 self.data = None6364 #: Dictionary or byte of querystring data to attach to the63 #: :class:`Request <models.Request>`.65 #: :class:`Request <Request>`.66 self.params = None6766 #: True if :class:`Request <models.Request>` is part of a redirect chain (disables history68 #: True if :class:`Request <Request>` is part of a redirect chain (disables history69 #: and HTTPError storage).70 self.redirect = redirect7172 #: Set to True if full redirects are allowed (e.g. re-POST-ing of data at new ``Location``)
4 unmodified lines
7778 self.data, self._enc_data = self._encode_params(data)79 self.params, self._enc_params = self._encode_params(params)8079 #: :class:`Response <models.Response>` instance, containing81 #: :class:`Response <Response>` instance, containing82 #: content and metadata of HTTP Response, once :attr:`sent <send>`.83 self.response = Response()8485 if isinstance(auth, (list, tuple)):86 auth = AuthObject(*auth)87 if not auth:88 auth = auth_manager.get_auth(self.url)8988 #: :class:`AuthObject` to attach to :class:`Request <models.Request>`.90 #: :class:`AuthObject` to attach to :class:`Request <Request>`.91 self.auth = auth9291 #: CookieJar to attach to :class:`Request <models.Request>`.93 #: CookieJar to attach to :class:`Request <Request>`.94 self.cookiejar = cookiejar9596 #: True if Request has been sent.97 self.sent = False
37 unmodified lines
135 if self.cookiejar is not None:136 _handlers.append(urllib2.HTTPCookieProcessor(self.cookiejar))137138 if self.auth:137 if not isinstance(self.auth.handler, (urllib2.AbstractBasicAuthHandler, urllib2.AbstractDigestAuthHandler)):139 if not isinstance(self.auth.handler,140 (urllib2.AbstractBasicAuthHandler,141 urllib2.AbstractDigestAuthHandler)):142143 # TODO: REMOVE THIS COMPLETELY139 auth_manager.add_password(self.auth.realm, self.url, self.auth.username, self.auth.password)144 auth_manager.add_password(145 self.auth.realm, self.url,146 self.auth.username,147 self.auth.password)148149 self.auth.handler = self.auth.handler(auth_manager)150 auth_manager.add_auth(self.url, self.auth)151152 _handlers.append(self.auth.handler)
23 unmodified lines
176 return opener.open177178179 def _build_response(self, resp, is_error=False):171 """Build internal :class:`Response <models.Response>` object from given response."""180 """Build internal :class:`Response <Response>` object181 from given response.182 """183184185 def build(resp):186187 response = Response()188 response.status_code = getattr(resp, 'code', None)189190 try:191 response.headers = CaseInsensitiveDict(getattr(resp.info(), 'dict', None))180 response.read = resp.read181 response._resp = resp182 response._close = resp.close192 response.raw = resp193194 if self.cookiejar:195 response.cookies = dict_from_cookiejar(self.cookiejar)196
19 unmodified lines
216 ('location' in r.headers) and217 ((r.status_code is codes.see_other) or (self.allow_redirects))218 ):219210 r.close()220 r.raw.close()221222 if not len(history) < settings.max_redirects:223 raise TooManyRedirects()224
40 unmodified lines
265 version of that.266267 Otherwise, assumes the data is already encoded appropriately, and268 returns it twice.259269 """270271 if hasattr(data, 'items'):272 result = []273 for k, vs in data.items():274 for v in isinstance(vs, list) and vs or [vs]:
35 unmodified lines
310 already been sent.311 """312313 self._checks()304 success = False314315 # Logging316 if settings.verbose:317 settings.verbose.write('%s %s %s\n' % (
57 unmodified lines
375 why = Timeout(why)376377 self._build_response(why, is_error=True)378370379 else:380 self._build_response(resp)381 self.response.ok = True382
2 unmodified lines
385386 return self.sent387388381389class Response(object):383 """The core :class:`Response <models.Response>` object. All384 :class:`Request <models.Request>` objects contain a385 :class:`response <models.Response>` attribute, which is an instance390 """The core :class:`Response <Response>` object. All391 :class:`Request <Request>` objects contain a392 :class:`response <Response>` attribute, which is an instance393 of this class.394 """395396 def __init__(self):390 #: Raw content of the response, in bytes.391 #: If ``content-encoding`` of response was set to ``gzip``, the392 #: response data will be automatically deflated.397398 self._content = None399 self._content_consumed = False400401 #: Integer Code of responded HTTP Status.402 self.status_code = None403404 #: Case-insensitive Dictionary of Response Headers.405 #: For example, ``headers['content-encoding']`` will return the406 #: value of a ``'Content-Encoding'`` response header.407 self.headers = CaseInsensitiveDict()408409 #: File-like object representation of response (for advanced usage).410 self.raw = None411412 #: Final URL location of Response.413 self.url = None414415 #: True if no :attr:`error` occured.416 self.ok = False417418 #: Resulting :class:`HTTPError` of request, if one occured.419 self.error = None420406 #: A list of :class:`Response <models.Response>` objects from421 #: A list of :class:`Response <Response>` objects from422 #: the history of the Request. Any redirect responses will end423 #: up here.424 self.history = []425410 #: The Request that created the Response.426 #: The :class:`Request <Request>` that created the Response.427 self.request = None428429 #: A dictionary of Cookies the server sent back.430 self.cookies = None431432
2 unmodified lines
435436437 def __nonzero__(self):438 """Returns true if :attr:`status_code` is 'OK'."""439440 return not self.error441442 def iter_content(self, chunk_size=10 * 1024, decode_unicode=None):443 """Iterates over the response data. This avoids reading the content444 at once into memory for large responses. The chunk size is the number445 of bytes it should read into memory. This is not necessarily the446 length of each item returned as decoding can take place.447 """448 if self._content_consumed:449 raise RuntimeError('The content for this response was '450 'already consumed')451425 def __getattr__(self, name):426 """Read and returns the full stream when accessing to :attr: `content`"""427 if name == 'content':428 if self._content is not None:429 return self._content430 self._content = self.read()431 if self.headers.get('content-encoding', '') == 'gzip':432 try:433 self._content = zlib.decompress(self._content, 16+zlib.MAX_WBITS)434 except zlib.error:435 pass452 def generate():453 while 1:454 chunk = self.raw.read(chunk_size)455 if not chunk:456 break457 yield chunk458 self._content_consumed = True459 gen = generate()460 if 'gzip' in self.headers.get('content-encoding', ''):461 gen = stream_decode_gzip(gen)462 if decode_unicode is None:463 decode_unicode = settings.decode_unicode464 if decode_unicode:465 gen = stream_decode_response_unicode(gen, self)466 return gen467468 @property469 def content(self):470 """Content of the response, in bytes or unicode471 (if available).472 """473474 if self._content is not None:475 return self._content437 else:438 raise AttributeError476477 if self._content_consumed:478 raise RuntimeError('The content for this response was '479 'already consumed')480481 # Read the contents.482 self._content = self.raw.read()483484 # Decode GZip'd content.485 if 'gzip' in self.headers.get('content-encoding', ''):486 try:487 self._content = decode_gzip(self._content)488 except zlib.error:489 pass490491 # Decode unicode content.492 if settings.decode_unicode:493 self._content = get_unicode_from_response(self)494495 self._content_consumed = True496 return self._content497498499 def raise_for_status(self):500 """Raises stored :class:`HTTPError` or :class:`URLError`, if one occured."""501 if self.error:502 raise self.error503504446 def close(self):447 if self._resp.fp is not None and hasattr(self._resp.fp, '_sock'):448 self._resp.fp._sock.recv = None449 self._close()505506class AuthManager(object):507 """Requests Authentication Manager."""508
171 unmodified lines
modified:requests/utils.py+187 added-5 removed
7 unmodified lines
8that are also useful for external consumption.910"""1112import cgi13import codecs14import cookielib15import re16import zlib171815def dict_from_cookiejar(cookiejar):16 """Returns a key/value dictionary from a CookieJar."""19def header_expand(headers):20 """Returns an HTTP Header value string from a dictionary.2122 Example expansion::2324 {'text/x-dvi': {'q': '.8', 'mxb': '100000', 'mxt': '5.0'}, 'text/x-c': {}}25 # Accept: text/x-dvi; q=.8; mxb=100000; mxt=5.0, text/x-c2627 (('text/x-dvi', {'q': '.8', 'mxb': '100000', 'mxt': '5.0'}), ('text/x-c', {}))28 # Accept: text/x-dvi; q=.8; mxb=100000; mxt=5.0, text/x-c29 """3031 collector = []3233 if isinstance(headers, dict):34 headers = headers.items()3536 elif isinstance(headers, basestring):37 return headers3839 for i, (value, params) in enumerate(headers):4041 _params = []4243 for (p_k, p_v) in params.items():4445 _params.append('%s=%s' % (p_k, p_v))4647 collector.append(value)48 collector.append('; ')4950 if len(params):5152 collector.append('; '.join(_params))5354 if not len(headers) == i+1:55 collector.append(', ')565758 # Remove trailing seperators.59 if collector[-1] in (', ', '; '):60 del collector[-1]6162 return ''.join(collector)63646566def dict_from_cookiejar(cj):67 """Returns a key/value dictionary from a CookieJar.6869 :param cj: CookieJar object to extract cookies from.70 """7172 cookie_dict = {}7320 for _, cookies in cookiejar._cookies.items():74 for _, cookies in cj._cookies.items():75 for _, cookies in cookies.items():76 for cookie in cookies.values():77 # print cookie78 cookie_dict[cookie.name] = cookie.value
1 unmodified line
80 return cookie_dict818283def cookiejar_from_dict(cookie_dict):30 """Returns a CookieJar from a key/value dictionary."""84 """Returns a CookieJar from a key/value dictionary.8586 :param cookie_dict: Dict of key/values to insert into CookieJar.87 """8889 # return cookiejar if one was passed in90 if isinstance(cookie_dict, cookielib.CookieJar):91 return cookie_dict92
5 unmodified lines
98 return cj99100101def add_dict_to_cookiejar(cj, cookie_dict):45 """Returns a CookieJar from a key/value dictionary."""102 """Returns a CookieJar from a key/value dictionary.103104 :param cj: CookieJar to insert cookies into.105 :param cookie_dict: Dict of key/values to insert into CookieJar.106 """107108 for k, v in cookie_dict.items():109110 cookie = cookielib.Cookie(111 version=0,
18 unmodified lines
130 # add cookie to cookiejar131 cj.set_cookie(cookie)132133 return cj134135136def get_encodings_from_content(content):137 """Returns encodings from given content string.138139 :param content: bytestring to extract encodings from.140 """141142 charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)143144 return charset_re.findall(content)145146147def get_encoding_from_headers(headers):148 """Returns encodings from given HTTP Header Dict.149150 :param headers: dictionary to extract encoding from.151 """152153 content_type = headers.get('content-type')154155 if not content_type:156 return None157158 content_type, params = cgi.parse_header(content_type)159160 if 'charset' in params:161 return params['charset'].strip("'\"")162163164def unicode_from_html(content):165 """Attempts to decode an HTML string into unicode.166 If unsuccessful, the original content is returned.167 """168169 encodings = get_encodings_from_content(content)170171 for encoding in encodings:172173 try:174 return unicode(content, encoding)175 except (UnicodeError, TypeError):176 pass177178 return content179180181def stream_decode_response_unicode(iterator, r):182 """Stream decodes a iterator."""183 encoding = get_encoding_from_headers(r.headers)184 if encoding is None:185 for item in iterator:186 yield item187 return188189 decoder = codecs.getincrementaldecoder(encoding)(errors='replace')190 for chunk in iterator:191 rv = decoder.decode(chunk)192 if rv:193 yield rv194 rv = decoder.decode('', final=True)195 if rv:196 yield rv197198199def get_unicode_from_response(r):200 """Returns the requested content back in unicode.201202 :param r: Reponse object to get unicode content from.203204 Tried:205206 1. charset from content-type207208 2. every encodings from ``<meta ... charset=XXX>``209210 3. fall back and replace all unicode characters211212 """213214 tried_encodings = []215216 # Try charset from content-type217 encoding = get_encoding_from_headers(r.headers)218219 if encoding:220 try:221 return unicode(r.content, encoding)222 except UnicodeError:223 tried_encodings.append(encoding)224225 # Fall back:226 try:227 return unicode(r.content, encoding, errors='replace')228 except TypeError:229 return r.content230231232def decode_gzip(content):233 """Return gzip-decoded string.234235 :param content: bytestring to gzip-decode.236 """237238 return zlib.decompress(content, 16 + zlib.MAX_WBITS)239240241def stream_decode_gzip(iterator):242 """Stream decodes a gzip-encoded iterator"""243 try:244 dec = zlib.decompressobj(16 + zlib.MAX_WBITS)245 for chunk in iterator:246 rv = dec.decompress(chunk)247 if rv:248 yield rv249 buf = dec.decompress('')250 rv = buf + dec.flush()251 if rv:252 yield rv253 except zlib.error:254 pass
modified:AUTHORS+4 added
38 unmodified lines
39- Shrikant Sharat Kandula40- Mikko Ohtamaa41- Den Shabalin42- Daniel Miller <danielm@vs-networks.com>43- Alejandro Giacometti44- Rick Mak45- Johan Bergström46- Josselin Jacquard
deleted:AUTHORS.orig-40 removed
1Requests is written and maintained by Kenneth Reitz and2various contributors:34Development Lead5````````````````67- Kenneth Reitz <me@kennethreitz.com>8910Patches and Suggestions11```````````````````````1213- Various Pocoo Members14- Chris Adams15- Flavio Percoco Premoli16- Dj Gilcrease17- Justin Murphy18- Rob Madole19- Aram Dulyan20- Johannes Gorset21- 村山めがね (Megane Murayama)22- James Rowe23- Daniel Schauenberg24- Zbigniew Siciarz25- Daniele Tricoli 'Eriol'26- Richard Boulton27- Miguel Olivares <miguel@moliware.com>28- Alberto Paro29- Jérémy Bethmont30- 潘旭 (Xu Pan)31- Tamás Gulácsi32- Rubén Abad33- Peter Manser34- Jeremy Selie35<<<<<<< HEAD36- Jens Diemer37- Alex <@alopatin>38=======39- Tom Hogans <tomhsx@gmail.com>40>>>>>>> 0ed641a26ec2200de00e4bbf3d170c767375351e
modified:HISTORY.rst+9 added-1 removed
1History2-------340.6.4 (2011-10-13)5++++++++++++++++++67* Automatic decoding of unicode, based on HTTP Headers.8* New ``decode_unicode`` setting9* Removal of ``r.read/close`` methods10* New ``r.faw`` interface for advanced response usage.*11* Automatic expansion of parameterized headers12130.6.3 (2011-10-13)14++++++++++++++++++1516* Beautiful ``requests.async`` module, for making async requests w/ gevent.179180.6.2 (2011-10-09)19++++++++++++++++++2021* GET/HEAD obeys allow_redirects=False
160 unmodified lines
modified:MANIFEST.in+1 added-1 removed
1include README.rst LICENSE HISTORY.rst 1include README.rst LICENSE HISTORY.rst test_requests.py
modified:test_requests.py+7 added-1 removed
60 unmodified lines
61 def test_HTTP_200_OK_GET(self):62 r = requests.get(httpbin('/'))63 self.assertEqual(r.status_code, 200)6465 def test_HTTP_302_ALLOW_REDIRECT_GET(self):66 r = requests.get(httpbin('redirect', '1'))67 self.assertEqual(r.status_code, 200)6869 def test_HTTP_302_GET(self):70 r = requests.get(httpbin('redirect', '1'), allow_redirects=False)71 self.assertEqual(r.status_code, 302)7273 def test_HTTPS_200_OK_GET(self):74 r = requests.get(httpsbin('/'))75 self.assertEqual(r.status_code, 200)76
419 unmodified lines
496 assert heads['User-agent'] in r2.content497 self.assertEqual(r2.status_code, 200)498499493500if __name__ == '__main__':501 unittest.main()