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
Provenance
- Commit
46f0146- Tree
dc64f63- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
b14fa07- Parent 2
0d6773c
13 files changed+363 added−139 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 added
47 unmodified lines48 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 52+Support for Python 3.x is planned.53+Support for Python 3.x is planned.modified:requests/api.py+42 added-41 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`.6 unmodified lines39 :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 """42 43+ method = str(method).upper()44+45 if cookies is None:46 cookies = {}47 48 cookies = cookiejar_from_dict(cookies)49 50+ # Expand header values51+ if headers:52+ for k, v in headers.items() or {}:53+ headers[k] = header_expand(v)54+55 args = dict(56 method = method,57 url = url,58 data = data,41 unmodified lines100 :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 """114 115+ 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"] = True120 121+ return request('get', url, **kwargs)122 105-def head(url, **kwargs):123 124+def head(url, **kwargs):125 """Sends a HEAD request. Returns :class:`Response` object.126 127 :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 """143 144+ 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"] = True149 150+ return request('head', url, **kwargs)151 123-def post(url, data='', **kwargs):152 153+def post(url, data='', **kwargs):154 """Sends a POST request. Returns :class:`Response` object.155 156 :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 """160 139- return request('POST', url, data=data, **kwargs)161+ return request('post', url, data=data, **kwargs)162 163 164 def put(url, data='', **kwargs):165 """Sends a PUT request. Returns :class:`Response` object.166 167 :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 """171 157- return request('PUT', url, data=data, **kwargs)172+ return request('put', url, data=data, **kwargs)173 174 175 def patch(url, data='', **kwargs):176 """Sends a PATCH request. Returns :class:`Response` object.177 178 :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 """182 175- return request('PATCH', url, **kwargs)183+ return request('patch', url, **kwargs)184 185 186 def delete(url, **kwargs):179-187 """Sends a DELETE request. Returns :class:`Response` object.188 189 :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 """192 192- return request('DELETE', url, **kwargs)193+ 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+107 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.fo = resp193 194 if self.cookiejar:195 response.cookies = dict_from_cookiejar(self.cookiejar)196 16 unmodified lines213 if r.status_code in REDIRECT_STATI and not self.redirect:214 215 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 ):224 210- r.close()225+ r.fo.close()226 227 if not len(history) < settings.max_redirects:228 raise TooManyRedirects()229 40 unmodified lines270 version of that.271 272 Otherwise, assumes the data is already encoded appropriately, and273 returns it twice.259-274 """275+276 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 lines315 already been sent.316 """317 318 self._checks()304- success = False319 320 # Logging321 if settings.verbose:322 settings.verbose.write('%s %s %s\n' % (57 unmodified lines380 why = Timeout(why)381 382 self._build_response(why, is_error=True)383 370-384 else:385 self._build_response(resp)386 self.response.ok = True387 2 unmodified lines390 391 return self.sent392 393 381-394 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 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 """400 401 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.402+403 self._content = None404+ self._content_consumed = False405+406 #: Integer Code of responded HTTP Status.407 self.status_code = None408+409 #: 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()413+414+ #: File-like object representation of response (for advanced usage).415+ self.fo = None416+417 #: Final URL location of Response.418 self.url = None419+420 #: True if no :attr:`error` occured.421 self.ok = False422+423 #: Resulting :class:`HTTPError` of request, if one occured.424 self.error = None425+406- #: 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 = []430+410- #: The Request that created the Response.431+ #: The :class:`Request <Request>` that created the Response.432 self.request = None433+434 #: A dictionary of Cookies the server sent back.435 self.cookies = None436 437 2 unmodified lines440 441 442 def __nonzero__(self):443 """Returns true if :attr:`status_code` is 'OK'."""444+445 return not self.error446 447+ 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')456 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- 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 gen472+473+ @property474+ def content(self):475+ """Content of the response, in bytes or unicode476+ (if available).477+ """478+479+ if self._content is not None:480 return self._content437- else:438- raise AttributeError481 482+ if self._content_consumed:483+ raise RuntimeError('The content for this response was '484+ 'already consumed')485+486+ # Read the contents.487+ self._content = self.fo.read()488+489+ # 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+ pass495+496+ # Decode unicode content.497+ if settings.decode_unicode:498+ self._content = get_unicode_from_response(self)499+500+ self._content_consumed = True501+ return self._content502+503+504 def raise_for_status(self):505 """Raises stored :class:`HTTPError` or :class:`URLError`, if one occured."""506 if self.error:507 raise self.error508 509 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()510 511 class AuthManager(object):512 """Requests Authentication Manager."""513 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+6 added-1 removed
1 History2 -------3 4+* 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 headers9+10 0.6.3 (2011-10-13)11 ++++++++++++++++++12 13 * Beautiful ``requests.async`` module, for making async requests w/ gevent.14 9-15 0.6.2 (2011-10-09)16 ++++++++++++++++++17 18 * 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()