Skip to content
Myr

move encoding methods into utils for external consumption

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 7fc8c7c · Browse files · 1 file+61 added−0 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+61 added−0 removed

  • other:+61 added−0 removed

1 file+61 added−0 removed

modified:requests/utils.py+61 added
7 unmodified lines
8that are also useful for external consumption.910"""1112import cgi13import cookielib14import re151617def dict_from_cookiejar(cookiejar):18 """Returns a key/value dictionary from a CookieJar."""
52 unmodified lines
71 # add cookie to cookiejar72 cj.set_cookie(cookie)7374 return cj757677def get_encodings_from_content(content):78 """Returns encodings from given content string."""7980 charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)8182 return charset_re.findall(content)83848586def get_encoding_from_headers(headers):87 """Returns encodings from given HTTP Header Dict."""8889 content_type = headers.get('content-type')90 content_type, params = cgi.parse_header(content_type)9192 if 'charset' in params:93 return params['charset'].strip("'\"")949596def get_unicode_from_response(r):97 """Returns the requested content back in unicode.9899 Tried:100 1. charset from content-type101 2. every encodings from <meta ... charset=XXX>102 3. fall back and replace all unicode characters103 """104105 tried_encodings = []106107 # Try charset from content-type108 encoding = get_encoding_from_headers(r.headers)109110 if encoding:111 try:112 print '!'113 return unicode(r.content, encoding)114 except UnicodeError:115 tried_encodings.append(encoding)116117 # Try every encodings from <meta ... charset=XXX>118 encodings = get_encodings_from_content(r.content)119120 for encoding in encodings:121 if encoding in tried_encodings:122 continue123 try:124125 return unicode(r.content, encoding)126 except (UnicodeError, TypeError):127 tried_encodings.append(encoding)128129 # Fall back:130 try:131 return unicode(r.content, encoding, errors='replace')132 except TypeError:133 return r.content