move encoding detection out of request object.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kenneth Reitz · committed by Kenneth Reitz · parent 7eb272b · Browse files · 1 file·+23 added−52 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+23 added−52 removed
- other:+23 added−52 removed
Provenance
- Commit
7fc8c7c- Tree
72c4553- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
7eb272b
1 file changed+23 added−52 removed
modified:requests/models.py+23 added-52 removed
8 unmodified lines9 import urllib10 import urllib211 import socket12 import zlib13-import cgi14-import re13 14+15 from urllib2 import HTTPError16 from urlparse import urlparse, urlunparse, urljoin17 from datetime import datetime18 1 unmodified line20 from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPForcedBasicAuthHandler, HTTPDigestAuthHandler, HTTPRedirectHandler21 from .structures import CaseInsensitiveDict22 from .packages.poster.encode import multipart_encode23 from .packages.poster.streaminghttp import register_openers, get_handlers25-from .utils import dict_from_cookiejar26-from .exceptions import RequestException, AuthenticationError, Timeout, URLRequired, InvalidMethod, TooManyRedirects24+from .utils import dict_from_cookiejar, get_unicode_from_response25 from .status_codes import codes26+from .exceptions import RequestException, AuthenticationError, Timeout, URLRequired, InvalidMethod, TooManyRedirects27 28 29 REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)30 387 unmodified lines418 419 420 def __nonzero__(self):421 """Returns true if :attr:`status_code` is 'OK'."""422+423 return not self.error424 425 426 def __getattr__(self, name):427- """Read and returns the full stream when accessing to :attr: `content`"""427+ """Read and returns the full stream when accessing to428+ :attr: `content`429+ """430+431 if name == 'content':432 if self._content is not None:433 return self._content434+435+ # Read the contents.436 self._content = self.read()437+438+ # Decode GZip'd content.439 if self.headers.get('content-encoding', '') == 'gzip':440 try:441 self._content = zlib.decompress(self._content, 16+zlib.MAX_WBITS)442 except zlib.error:443 pass437- return self.unicode_content(self._content)444 439- 440- else:441- raise AttributeError442- 445+ # Decode unicode content.446+ try:447+ self._content = get_unicode_from_response(self)448+ # Don't trust this stuff.449+ except UserWarning, e:450+ print e451 444- def get_content_type(self):445- content_type = self.headers.get("content-type")446- content_type, params = cgi.parse_header(content_type)447- return content_type, params452 449- def get_encoding_from_content_type(self):450- content_type, params = self.get_content_type()451- if "charset" in params:452- return params["charset"].strip("'\"")453+ return self._content454 454- def get_encodings_from_content(self, content):455- if self._charset_re is None:456- self._charset_re = re.compile(457- r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I458- )459- return self._charset_re.findall(content)460- 461- def unicode_content(self, content):462- """463- Returns the requested content back in unicode.464- Tried:465- 1. charset from content-type466- 2. every encodings from <meta ... charset=XXX>467- 3. fall back and replace all unicode characters468- """469- tried_encodings = []470- # Try charset from content-type471- encoding = self.get_encoding_from_content_type()472- if encoding:473- try:474- return unicode(content, encoding)475- except UnicodeError:476- tried_encodings.append(encoding)455+ else:456+ raise AttributeError457 478- # Try every encodings from <meta ... charset=XXX>479- encodings = self.get_encodings_from_content(content)480- for encoding in encodings:481- if encoding in tried_encodings:482- continue483- try:484- return unicode(content, encoding)485- except UnicodeError:486- tried_encodings.append(encoding)458 488- # Fall back:489- return unicode(content, encoding, errors="replace")459 460 def raise_for_status(self):461 """Raises stored :class:`HTTPError` or :class:`URLError`, if one occured."""462 if self.error:4 unmodified lines467 if self._resp.fp is not None and hasattr(self._resp.fp, '_sock'):468 self._resp.fp._sock.recv = None469 self._close()470 471+472+473 class AuthManager(object):474 """Requests Authentication Manager."""475 476 def __new__(cls):170 unmodified lines