Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add auto detect charset from http body when http headers not seted #2161

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions AUTHORS.rst
Original file line number Diff line number Diff line change
Expand Up @@ -153,3 +153,4 @@ Patches and Suggestions
- Erik Wickstrom <erik@erikwickstrom.com> (`@erikwickstrom <https://github.com/erikwickstrom>`_)
- Константин Подшумок (`@podshumok <https://github.com/podshumok>`_)
- Ben Bass (`@codedstructure <https://github.com/codedstructure>`_)
- Li Kexian (`@likexian <https://github.com/likexian>`_)
13 changes: 12 additions & 1 deletion requests/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@
from .utils import (
guess_filename, get_auth_from_url, requote_uri,
stream_decode_response_unicode, to_key_val_list, parse_header_links,
iter_slices, guess_json_utf, super_len, to_native_string)
iter_slices, guess_json_utf, super_len, to_native_string,
get_encodings_from_content)
from .compat import (
cookielib, urlunparse, urlsplit, urlencode, str, bytes, StringIO,
is_py2, chardet, json, builtin_str, basestring)
Expand Down Expand Up @@ -709,6 +710,16 @@ def content(self):
except AttributeError:
self._content = None

# Fallback to auto-detected encoding.
if self.encoding is None or self.encoding == 'ISO-8859-1':
encoding_check = get_encodings_from_content(str(self._content, errors='replace'))
if len(encoding_check):
self.encoding = encoding_check[0]
else:
encoding_check = chardet.detect(self._content)
if encoding_check['confidence'] > 0.5:
self.encoding = encoding_check['encoding']

self._content_consumed = True
# don't need to release the connection; that's been handled by urllib3
# since we exhausted the data.
Expand Down
8 changes: 8 additions & 0 deletions test_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -1018,6 +1018,14 @@ def test_precedence(self):
encodings = requests.utils.get_encodings_from_content(content)
assert encodings == ['HTML5', 'HTML4', 'XML']

def test_no_charset_in_http_headers(self):
'''
This website's server don't response a charset encoding in the http headers
It shall auto detected from content with <head>'s charset or content chardet
'''
response = requests.get('http://www.126.com/')
assert response.encoding == 'utf-8'


class TestCaseInsensitiveDict(unittest.TestCase):

Expand Down