Skip to content
Myr

Merge branch 'feature-content-streaming' of https://github.com/mitsuhiko/requests into feature/content-stream

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

Conflicts: AUTHORS HISTORY.rst docs/api.rst docs/community/faq.rst docs/user/intro.rst requests/api.py requests/models.py

authored by Kenneth Reitz · committed by Kenneth Reitz · parents b14fa07, 0d6773c · Browse files · 13 files+363 added−139 removed
This commit

State

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

Diff stats

13 files+363 added−139 removed

  • other:+363 added−139 removed

13 files+363 added−139 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 added
47 unmodified lines
48 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.49505152Support for Python 3.x is planned.53Support for Python 3.x is planned.
modified:requests/api.py+42 added-41 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`.
6 unmodified lines
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 """4243 method = str(method).upper()4445 if cookies is None:46 cookies = {}4748 cookies = cookiejar_from_dict(cookies)4950 # Expand header values51 if headers:52 for k, v in headers.items() or {}:53 headers[k] = header_expand(v)5455 args = dict(56 method = method,57 url = url,58 data = data,
41 unmodified lines
100 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.101 :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.102 :param auth: (optional) AuthObject to enable Basic HTTP Auth.103 :param timeout: (optional) Float describing the timeout of the request.104 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.105 :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.106 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.107 :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.108 :param auth: (optional) AuthObject to enable Basic HTTP Auth.109 :param timeout: (optional) Float describing the timeout of the request.110 :param allow_redirects: (optional) Boolean. Set to False to disable redirect following.111 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.112 :param **kwargs: Optional arguments that ``request`` takes.113 """114115 return request('GET', url, **kwargs)116 kwargs.setdefault('allow_redirects', True)117 return request('GET', url, **kwargs)118 if "allow_redirects" not in kwargs:119 kwargs["allow_redirects"] = True120121 return request('get', url, **kwargs)122105def head(url, **kwargs):123124def head(url, **kwargs):125 """Sends a HEAD request. Returns :class:`Response` object.126127 :param url: URL for the new :class:`Request` object.128 :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.129 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.130 :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.131 :param auth: (optional) AuthObject to enable Basic HTTP Auth.132 :param timeout: (optional) Float describing the timeout of the request.133 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.134 :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.135 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.136 :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.137 :param auth: (optional) AuthObject to enable Basic HTTP Auth.138 :param timeout: (optional) Float describing the timeout of the request.139 :param allow_redirects: (optional) Boolean. Set to False to disable redirect following.140 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.141 :param **kwargs: Optional arguments that ``request`` takes.142 """143144 return request('HEAD', url, **kwargs)145 kwargs.setdefault('allow_redirects', True)146 return request('HEAD', url, **kwargs)147 if "allow_redirects" not in kwargs:148 kwargs["allow_redirects"] = True149150 return request('head', url, **kwargs)151123def post(url, data='', **kwargs):152153def post(url, data='', **kwargs):154 """Sends a POST request. Returns :class:`Response` object.155156 :param url: URL for the new :class:`Request` object.157 :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.158 :param **kwargs: Optional arguments that ``request`` takes.159 """160139 return request('POST', url, data=data, **kwargs)161 return request('post', url, data=data, **kwargs)162163164def put(url, data='', **kwargs):165 """Sends a PUT request. Returns :class:`Response` object.166167 :param url: URL for the new :class:`Request` object.168 :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.169 :param **kwargs: Optional arguments that ``request`` takes.170 """171157 return request('PUT', url, data=data, **kwargs)172 return request('put', url, data=data, **kwargs)173174175def patch(url, data='', **kwargs):176 """Sends a PATCH request. Returns :class:`Response` object.177178 :param url: URL for the new :class:`Request` object.179 :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.180 :param **kwargs: Optional arguments that ``request`` takes.181 """182175 return request('PATCH', url, **kwargs)183 return request('patch', url, **kwargs)184185186def delete(url, **kwargs):179187 """Sends a DELETE request. Returns :class:`Response` object.188189 :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.190 :param **kwargs: Optional arguments that ``request`` takes.191 """192192 return request('DELETE', url, **kwargs)193 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+107 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.fo = resp193194 if self.cookiejar:195 response.cookies = dict_from_cookiejar(self.cookiejar)196
16 unmodified lines
213 if r.status_code in REDIRECT_STATI and not self.redirect:214215 while (216 ('location' in r.headers) and217 ((self.method in ('GET', 'HEAD')) or218 (r.status_code is codes.see_other) or219 (self.allow_redirects))220 ((r.status_code is codes.see_other) or (self.allow_redirects))221 ((r.status_code is codes.see_other) or222 (self.allow_redirects))223 ):224210 r.close()225 r.fo.close()226227 if not len(history) < settings.max_redirects:228 raise TooManyRedirects()229
40 unmodified lines
270 version of that.271272 Otherwise, assumes the data is already encoded appropriately, and273 returns it twice.259274 """275276 if hasattr(data, 'items'):277 result = []278 for k, vs in data.items():279 for v in isinstance(vs, list) and vs or [vs]:
35 unmodified lines
315 already been sent.316 """317318 self._checks()304 success = False319320 # Logging321 if settings.verbose:322 settings.verbose.write('%s %s %s\n' % (
57 unmodified lines
380 why = Timeout(why)381382 self._build_response(why, is_error=True)383370384 else:385 self._build_response(resp)386 self.response.ok = True387
2 unmodified lines
390391 return self.sent392393381394class 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 instance395 """The core :class:`Response <Response>` object. All396 :class:`Request <Request>` objects contain a397 :class:`response <Response>` attribute, which is an instance398 of this class.399 """400401 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.402403 self._content = None404 self._content_consumed = False405406 #: Integer Code of responded HTTP Status.407 self.status_code = None408409 #: Case-insensitive Dictionary of Response Headers.410 #: For example, ``headers['content-encoding']`` will return the411 #: value of a ``'Content-Encoding'`` response header.412 self.headers = CaseInsensitiveDict()413414 #: File-like object representation of response (for advanced usage).415 self.fo = None416417 #: Final URL location of Response.418 self.url = None419420 #: True if no :attr:`error` occured.421 self.ok = False422423 #: Resulting :class:`HTTPError` of request, if one occured.424 self.error = None425406 #: A list of :class:`Response <models.Response>` objects from426 #: A list of :class:`Response <Response>` objects from427 #: the history of the Request. Any redirect responses will end428 #: up here.429 self.history = []430410 #: The Request that created the Response.431 #: The :class:`Request <Request>` that created the Response.432 self.request = None433434 #: A dictionary of Cookies the server sent back.435 self.cookies = None436437
2 unmodified lines
440441442 def __nonzero__(self):443 """Returns true if :attr:`status_code` is 'OK'."""444445 return not self.error446447 def iter_content(self, chunk_size=10 * 1024, decode_unicode=None):448 """Iterates over the response data. This avoids reading the content449 at once into memory for large responses. The chunk size is the number450 of bytes it should read into memory. This is not necessarily the451 length of each item returned as decoding can take place.452 """453 if self._content_consumed:454 raise RuntimeError('The content for this response was '455 'already consumed')456425 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 pass457 def generate():458 while 1:459 chunk = self.fo.read(chunk_size)460 if not chunk:461 break462 yield chunk463 self._content_consumed = True464 gen = generate()465 if 'gzip' in self.headers.get('content-encoding', ''):466 gen = stream_decode_gzip(gen)467 if decode_unicode is None:468 decode_unicode = settings.decode_unicode469 if decode_unicode:470 gen = stream_decode_response_unicode(gen, self)471 return gen472473 @property474 def content(self):475 """Content of the response, in bytes or unicode476 (if available).477 """478479 if self._content is not None:480 return self._content437 else:438 raise AttributeError481482 if self._content_consumed:483 raise RuntimeError('The content for this response was '484 'already consumed')485486 # Read the contents.487 self._content = self.fo.read()488489 # Decode GZip'd content.490 if 'gzip' in self.headers.get('content-encoding', ''):491 try:492 self._content = decode_gzip(self._content)493 except zlib.error:494 pass495496 # Decode unicode content.497 if settings.decode_unicode:498 self._content = get_unicode_from_response(self)499500 self._content_consumed = True501 return self._content502503504 def raise_for_status(self):505 """Raises stored :class:`HTTPError` or :class:`URLError`, if one occured."""506 if self.error:507 raise self.error508509446 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()510511class AuthManager(object):512 """Requests Authentication Manager."""513
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+6 added-1 removed
1History2-------34* Automatic decoding of unicode, based on HTTP Headers.5* New ``decode_unicode`` setting6* Removal of ``r.read/close`` methods7* New ``r.fo`` interface for advanced response usage.*8* Automatic expansion of parameterized headers9100.6.3 (2011-10-13)11++++++++++++++++++1213* Beautiful ``requests.async`` module, for making async requests w/ gevent.149150.6.2 (2011-10-09)16++++++++++++++++++1718* 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()