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
Provenance
- Commit
bfa0103- Tree
d9e99f5- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
b14fa07- Parent 2
daf7aeb
14 files changed+354 added−158 removed
modified:docs/community/faq.rst+1 added
8 unmodified lines9 -------------10 11 Requests automatically decompresses gzip-encoded responses, and does12 its best to decodes response content to unicode when possible.13+it's best to decodes response content to unicode when possible.14 15 You can get direct access to the raw response (and even the socket),16 if needed as well.17 67 unmodified linesmodified:docs/user/install.rst+1 added-1 removed
73 unmodified lines74 $ apt-get install libevent-dev75 76 Once you have ``libevent``, you can install ``gevent`` with ``pip``::77 78- $ pip install gevent78+ $ pip install geventmodified:docs/user/intro.rst-2 removed
45 unmodified lines46 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.47 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.49 50-51-modified:docs/api.rst+15 added-3 removed
29 unmodified lines30 31 .. autoclass:: Response32 :inherited-members:33 34+Async35+-----36 37+.. module:: requests.async38 39+40+.. autofunction:: map41+.. autofunction:: request42+.. autofunction:: head43+.. autofunction:: get44+.. autofunction:: post45+.. autofunction:: put46+.. autofunction:: patch47+.. autofunction:: delete48+49+50+51 Utilities52 ---------53 54 These functions are used internally, but may be useful outside of7 unmodified lines62 .. autofunction:: dict_from_cookiejar63 .. autofunction:: cookiejar_from_dict64 .. autofunction:: add_dict_to_cookiejar65 51-Curl52-~~~~53-.. autofunction:: curl_from_request66 67 Encodings68 ~~~~~~~~~69 36 unmodified linesmodified:requests/api.py+22 added-55 removed
13 unmodified lines14 import config15 from .models import Request, Response, AuthObject16 from .status_codes import codes17 from .hooks import dispatch_hook18-from .utils import cookiejar_from_dict18+from .utils import cookiejar_from_dict, header_expand19 20 21 __all__ = ('request', 'get', 'head', 'post', 'patch', 'put', 'delete')22 23 def 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):26 27- """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.29 30 :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 lines37 :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 """43 44+ method = str(method).upper()45+46 if cookies is None:47 cookies = {}48 49 cookies = cookiejar_from_dict(cookies)50 51+ # Expand header values52+ if headers:53+ for k, v in headers.items() or {}:54+ headers[k] = header_expand(v)55+56 args = dict(57 method = method,58 url = url,59 data = data,36 unmodified lines96 97 """Sends a GET request. Returns :class:`Response` object.98 99 :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 """102 103+104 kwargs.setdefault('allow_redirects', True)105 return request('GET', url, **kwargs)106 107 108 def head(url, **kwargs):106-109 """Sends a HEAD request. Returns :class:`Response` object.110 111 :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 """114 115 kwargs.setdefault('allow_redirects', True)116 return request('HEAD', url, **kwargs)117 118 119 def post(url, data='', **kwargs):124-120 """Sends a POST request. Returns :class:`Response` object.121 122 :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 """126 139- return request('POST', url, data=data, **kwargs)127+ return request('post', url, data=data, **kwargs)128 129 130 def put(url, data='', **kwargs):131 """Sends a PUT request. Returns :class:`Response` object.132 133 :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 """137 157- return request('PUT', url, data=data, **kwargs)138+ return request('put', url, data=data, **kwargs)139 140 141 def patch(url, data='', **kwargs):142 """Sends a PATCH request. Returns :class:`Response` object.143 144 :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 """148 175- return request('PATCH', url, **kwargs)149+ return request('patch', url, **kwargs)150 151 152 def delete(url, **kwargs):179-153 """Sends a DELETE request. Returns :class:`Response` object.154 155 :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 """158 192- return request('DELETE', url, **kwargs)159+ return request('delete', url, **kwargs)modified:requests/config.py+1 added
60 unmodified lines61 settings.proxies = None62 settings.verbose = None63 settings.timeout = None64 settings.max_redirects = 3065+settings.decode_unicode = True66 67 #: Use socket.setdefaulttimeout() as fallback?68 settings.timeout_fallback = Truemodified:requests/core.py+4 added-2 removed
17 unmodified lines18 __license__ = 'ISC'19 __copyright__ = 'Copyright 2011 Kenneth Reitz'20 21 22-from models import HTTPError22+from models import HTTPError, Request, Response23 from api import *24 from exceptions import *25 from sessions import session26 from status_codes import codes27-from config import settings27+from config import settings28+29+import utilsmodified:requests/models.py+102 added-47 removed
7 unmodified lines8 9 import urllib10 import urllib211 import socket12+import codecs13 import zlib14 15+16 from urllib2 import HTTPError17 from urlparse import urlparse, urlunparse, urljoin18 from datetime import datetime19 1 unmodified line21 from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPForcedBasicAuthHandler, HTTPDigestAuthHandler, HTTPRedirectHandler22 from .structures import CaseInsensitiveDict23 from .packages.poster.encode import multipart_encode24 from .packages.poster.streaminghttp import register_openers, get_handlers23-from .utils import dict_from_cookiejar24-from .exceptions import RequestException, AuthenticationError, Timeout, URLRequired, InvalidMethod, TooManyRedirects25+from .utils import dict_from_cookiejar, get_unicode_from_response, stream_decode_response_unicode, decode_gzip, stream_decode_gzip26 from .status_codes import codes27+from .exceptions import RequestException, AuthenticationError, Timeout, URLRequired, InvalidMethod, TooManyRedirects28 29 30 REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)31 32 33 34 class 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 """38 39 def __init__(self,7 unmodified lines47 48 #: Request URL.49 self.url = url50 49- #: 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 = headers53 54 #: Dictionary of files to multipart upload (``{filename: content}``).55 self.files = files56 55- #: HTTP Method to use. Available: GET, HEAD, PUT, POST, DELETE.57+ #: HTTP Method to use.58 self.method = method59 60 #: Dictionary or byte of request body data to attach to the59- #: :class:`Request <models.Request>`.61+ #: :class:`Request <Request>`.62 self.data = None63 64 #: Dictionary or byte of querystring data to attach to the63- #: :class:`Request <models.Request>`.65+ #: :class:`Request <Request>`.66 self.params = None67 66- #: 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 = redirect71 72 #: Set to True if full redirects are allowed (e.g. re-POST-ing of data at new ``Location``)4 unmodified lines77 78 self.data, self._enc_data = self._encode_params(data)79 self.params, self._enc_params = self._encode_params(params)80 79- #: :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()84 85 if isinstance(auth, (list, tuple)):86 auth = AuthObject(*auth)87 if not auth:88 auth = auth_manager.get_auth(self.url)89 88- #: :class:`AuthObject` to attach to :class:`Request <models.Request>`.90+ #: :class:`AuthObject` to attach to :class:`Request <Request>`.91 self.auth = auth92 91- #: CookieJar to attach to :class:`Request <models.Request>`.93+ #: CookieJar to attach to :class:`Request <Request>`.94 self.cookiejar = cookiejar95 96 #: True if Request has been sent.97 self.sent = False37 unmodified lines135 if self.cookiejar is not None:136 _handlers.append(urllib2.HTTPCookieProcessor(self.cookiejar))137 138 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)):142+143 # 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)148+149 self.auth.handler = self.auth.handler(auth_manager)150 auth_manager.add_auth(self.url, self.auth)151 152 _handlers.append(self.auth.handler)23 unmodified lines176 return opener.open177 178 179 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+ """183 184+185 def build(resp):186 187 response = Response()188 response.status_code = getattr(resp, 'code', None)189 190 try:191 response.headers = CaseInsensitiveDict(getattr(resp.info(), 'dict', None))180- response.read = resp.read181- response._resp = resp182- response._close = resp.close192+ response.raw = resp193 194 if self.cookiejar:195 response.cookies = dict_from_cookiejar(self.cookiejar)196 19 unmodified lines216 ('location' in r.headers) and217 ((r.status_code is codes.see_other) or (self.allow_redirects))218 ):219 210- r.close()220+ r.raw.close()221 222 if not len(history) < settings.max_redirects:223 raise TooManyRedirects()224 40 unmodified lines265 version of that.266 267 Otherwise, assumes the data is already encoded appropriately, and268 returns it twice.259-269 """270+271 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 lines310 already been sent.311 """312 313 self._checks()304- success = False314 315 # Logging316 if settings.verbose:317 settings.verbose.write('%s %s %s\n' % (57 unmodified lines375 why = Timeout(why)376 377 self._build_response(why, is_error=True)378 370-379 else:380 self._build_response(resp)381 self.response.ok = True382 2 unmodified lines385 386 return self.sent387 388 381-389 class 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 """395 396 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.397+398 self._content = None399+ self._content_consumed = False400+401 #: Integer Code of responded HTTP Status.402 self.status_code = None403+404 #: 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()408+409+ #: File-like object representation of response (for advanced usage).410+ self.raw = None411+412 #: Final URL location of Response.413 self.url = None414+415 #: True if no :attr:`error` occured.416 self.ok = False417+418 #: Resulting :class:`HTTPError` of request, if one occured.419 self.error = None420+406- #: 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 = []425+410- #: The Request that created the Response.426+ #: The :class:`Request <Request>` that created the Response.427 self.request = None428+429 #: A dictionary of Cookies the server sent back.430 self.cookies = None431 432 2 unmodified lines435 436 437 def __nonzero__(self):438 """Returns true if :attr:`status_code` is 'OK'."""439+440 return not self.error441 442+ 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')451 425- 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 gen467+468+ @property469+ def content(self):470+ """Content of the response, in bytes or unicode471+ (if available).472+ """473+474+ if self._content is not None:475 return self._content437- else:438- raise AttributeError476 477+ if self._content_consumed:478+ raise RuntimeError('The content for this response was '479+ 'already consumed')480+481+ # Read the contents.482+ self._content = self.raw.read()483+484+ # 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+ pass490+491+ # Decode unicode content.492+ if settings.decode_unicode:493+ self._content = get_unicode_from_response(self)494+495+ self._content_consumed = True496+ return self._content497+498+499 def raise_for_status(self):500 """Raises stored :class:`HTTPError` or :class:`URLError`, if one occured."""501 if self.error:502 raise self.error503 504 446- 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()505 506 class AuthManager(object):507 """Requests Authentication Manager."""508 171 unmodified linesmodified:requests/utils.py+187 added-5 removed
7 unmodified lines8 that are also useful for external consumption.9 10 """11 12+import cgi13+import codecs14 import cookielib15+import re16+import zlib17 18 15-def dict_from_cookiejar(cookiejar):16- """Returns a key/value dictionary from a CookieJar."""19+def header_expand(headers):20+ """Returns an HTTP Header value string from a dictionary.21 22+ Example expansion::23+24+ {'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-c26+27+ (('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+ """30+31+ collector = []32+33+ if isinstance(headers, dict):34+ headers = headers.items()35+36+ elif isinstance(headers, basestring):37+ return headers38+39+ for i, (value, params) in enumerate(headers):40+41+ _params = []42+43+ for (p_k, p_v) in params.items():44+45+ _params.append('%s=%s' % (p_k, p_v))46+47+ collector.append(value)48+ collector.append('; ')49+50+ if len(params):51+52+ collector.append('; '.join(_params))53+54+ if not len(headers) == i+1:55+ collector.append(', ')56+57+58+ # Remove trailing seperators.59+ if collector[-1] in (', ', '; '):60+ del collector[-1]61+62+ return ''.join(collector)63+64+65+66+def dict_from_cookiejar(cj):67+ """Returns a key/value dictionary from a CookieJar.68+69+ :param cj: CookieJar object to extract cookies from.70+ """71+72 cookie_dict = {}73 20- 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.value1 unmodified line80 return cookie_dict81 82 83 def cookiejar_from_dict(cookie_dict):30- """Returns a CookieJar from a key/value dictionary."""84+ """Returns a CookieJar from a key/value dictionary.85 86+ :param cookie_dict: Dict of key/values to insert into CookieJar.87+ """88+89 # return cookiejar if one was passed in90 if isinstance(cookie_dict, cookielib.CookieJar):91 return cookie_dict92 5 unmodified lines98 return cj99 100 101 def 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.103 104+ :param cj: CookieJar to insert cookies into.105+ :param cookie_dict: Dict of key/values to insert into CookieJar.106+ """107+108 for k, v in cookie_dict.items():109 110 cookie = cookielib.Cookie(111 version=0,18 unmodified lines130 # add cookie to cookiejar131 cj.set_cookie(cookie)132 133 return cj134+135+136+def get_encodings_from_content(content):137+ """Returns encodings from given content string.138+139+ :param content: bytestring to extract encodings from.140+ """141+142+ charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)143+144+ return charset_re.findall(content)145+146+147+def get_encoding_from_headers(headers):148+ """Returns encodings from given HTTP Header Dict.149+150+ :param headers: dictionary to extract encoding from.151+ """152+153+ content_type = headers.get('content-type')154+155+ if not content_type:156+ return None157+158+ content_type, params = cgi.parse_header(content_type)159+160+ if 'charset' in params:161+ return params['charset'].strip("'\"")162+163+164+def unicode_from_html(content):165+ """Attempts to decode an HTML string into unicode.166+ If unsuccessful, the original content is returned.167+ """168+169+ encodings = get_encodings_from_content(content)170+171+ for encoding in encodings:172+173+ try:174+ return unicode(content, encoding)175+ except (UnicodeError, TypeError):176+ pass177+178+ return content179+180+181+def 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+ return188+189+ 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 rv197+198+199+def get_unicode_from_response(r):200+ """Returns the requested content back in unicode.201+202+ :param r: Reponse object to get unicode content from.203+204+ Tried:205+206+ 1. charset from content-type207+208+ 2. every encodings from ``<meta ... charset=XXX>``209+210+ 3. fall back and replace all unicode characters211+212+ """213+214+ tried_encodings = []215+216+ # Try charset from content-type217+ encoding = get_encoding_from_headers(r.headers)218+219+ if encoding:220+ try:221+ return unicode(r.content, encoding)222+ except UnicodeError:223+ tried_encodings.append(encoding)224+225+ # Fall back:226+ try:227+ return unicode(r.content, encoding, errors='replace')228+ except TypeError:229+ return r.content230+231+232+def decode_gzip(content):233+ """Return gzip-decoded string.234+235+ :param content: bytestring to gzip-decode.236+ """237+238+ return zlib.decompress(content, 16 + zlib.MAX_WBITS)239+240+241+def 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+ passmodified:AUTHORS+4 added
38 unmodified lines39 - Shrikant Sharat Kandula40 - Mikko Ohtamaa41 - Den Shabalin42 - Daniel Miller <danielm@vs-networks.com>43+- Alejandro Giacometti44+- Rick Mak45+- Johan Bergström46+- Josselin Jacquarddeleted:AUTHORS.orig-40 removed
1-Requests is written and maintained by Kenneth Reitz and2-various contributors:3-4-Development Lead5-````````````````6-7-- Kenneth Reitz <me@kennethreitz.com>8-9-10-Patches and Suggestions11-```````````````````````12-13-- 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->>>>>>> 0ed641a26ec2200de00e4bbf3d170c767375351emodified:HISTORY.rst+9 added-1 removed
1 History2 -------3 4+0.6.4 (2011-10-13)5+++++++++++++++++++6+7+* 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 headers12+13 0.6.3 (2011-10-13)14 ++++++++++++++++++15 16 * Beautiful ``requests.async`` module, for making async requests w/ gevent.17 9-18 0.6.2 (2011-10-09)19 ++++++++++++++++++20 21 * GET/HEAD obeys allow_redirects=False160 unmodified linesmodified:MANIFEST.in+1 added-1 removed
1-include README.rst LICENSE HISTORY.rst 1+include README.rst LICENSE HISTORY.rst test_requests.pymodified:test_requests.py+7 added-1 removed
60 unmodified lines61 def test_HTTP_200_OK_GET(self):62 r = requests.get(httpbin('/'))63 self.assertEqual(r.status_code, 200)64 65+ def test_HTTP_302_ALLOW_REDIRECT_GET(self):66+ r = requests.get(httpbin('redirect', '1'))67+ self.assertEqual(r.status_code, 200)68 69+ def test_HTTP_302_GET(self):70+ r = requests.get(httpbin('redirect', '1'), allow_redirects=False)71+ self.assertEqual(r.status_code, 302)72+73 def test_HTTPS_200_OK_GET(self):74 r = requests.get(httpsbin('/'))75 self.assertEqual(r.status_code, 200)76 419 unmodified lines496 assert heads['User-agent'] in r2.content497 self.assertEqual(r2.status_code, 200)498 499 493-500 if __name__ == '__main__':501 unittest.main()