Skip to content
Myr

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

1 file+23 added−52 removed

modified:requests/models.py+23 added-52 removed
8 unmodified lines
9import urllib10import urllib211import socket12import zlib13import cgi14import re131415from urllib2 import HTTPError16from urlparse import urlparse, urlunparse, urljoin17from datetime import datetime18
1 unmodified line
20from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPForcedBasicAuthHandler, HTTPDigestAuthHandler, HTTPRedirectHandler21from .structures import CaseInsensitiveDict22from .packages.poster.encode import multipart_encode23from .packages.poster.streaminghttp import register_openers, get_handlers25from .utils import dict_from_cookiejar26from .exceptions import RequestException, AuthenticationError, Timeout, URLRequired, InvalidMethod, TooManyRedirects24from .utils import dict_from_cookiejar, get_unicode_from_response25from .status_codes import codes26from .exceptions import RequestException, AuthenticationError, Timeout, URLRequired, InvalidMethod, TooManyRedirects272829REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)30
387 unmodified lines
418419420 def __nonzero__(self):421 """Returns true if :attr:`status_code` is 'OK'."""422423 return not self.error424425426 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 """430431 if name == 'content':432 if self._content is not None:433 return self._content434435 # Read the contents.436 self._content = self.read()437438 # 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)444439 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 e451444 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, params452449 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._content454454 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 AttributeError457478 # 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)458488 # Fall back:489 return unicode(content, encoding, errors="replace")459460 def raise_for_status(self):461 """Raises stored :class:`HTTPError` or :class:`URLError`, if one occured."""462 if self.error:
4 unmodified lines
467 if self._resp.fp is not None and hasattr(self._resp.fp, '_sock'):468 self._resp.fp._sock.recv = None469 self._close()470471472473class AuthManager(object):474 """Requests Authentication Manager."""475476 def __new__(cls):
170 unmodified lines