Skip to content

Look at the charset of the content type of the handle to determine the encoding for io.TextIoWrapper - #1429

Merged
peterjc merged 7 commits into
biopython:masterfrom
BioGeek:master
Oct 27, 2017
Merged

peterjc merged 7 commits into
biopython:masterfrom
BioGeek:master

Conversation

@BioGeek

@BioGeek BioGeek commented Oct 26, 2017

Copy link
Copy Markdown
Contributor

This pull request addresses issue #1402.

I think the root cause is as follows:

  • the handle that Entrez.efetch returns under Python 3 is a io.TextIOWrapper object.
  • io.TextIOWrapper has an optional argument encoding . It defaults to locale.getpreferredencoding(False).
  • the encoding by NCBI of the record is in utf-8 (we presume).
  • If the locale.getpreferredencoding(False) of the user is not equal to utf-8, we get UnicodeDecodeErrors.

In the case that the record returned by NCBI is in XML format, then we can determine the encoding from the first line of the XML. But how do we determine the encoding of a record returned in text format?

Some digging in the code revealed that, in the function _binary_to_string_handle(handle) , the handle is a http.client.HTTPResponse object. This has a headers attribute which is a HTTPMessage object. In our case, it has the following Content-Type:

('Content-Type', 'text/plain; charset=UTF-8')

So, this pull request looks at the charset of the content type of the handle to determine the encoding. If no headersattribute is found, it falls back to the default behaviour and uses locale.getpreferredencoding(False).


I hereby agree to dual licence this and any previous contributions under both
the Biopython License Agreement AND the BSD 3-Clause License.

I am happy to be thanked by name in the NEWS.rst and
CONTRIB.rst files.

I have read the CONTRIBUTING.rst file and understand that AppVeyor and
TravisCI will be used to confirm the Biopython unit tests and flake8 style
checks pass with these changes.

@codecov

codecov Bot commented Oct 27, 2017 •

Copy link
Copy Markdown

Codecov Report

Merging #1429 into master will decrease coverage by <.01%.
The diff coverage is 16.66%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #1429      +/-   ##
==========================================
- Coverage   84.79%   84.78%   -0.01%     
==========================================
  Files         320      320              
  Lines       49051    49056       +5     
==========================================
+ Hits        41591    41594       +3     
- Misses       7460     7462       +2
Impacted Files Coverage Δ
Bio/_py3k/__init__.py 78.04% <16.66%> (-3.77%) ⬇️
Bio/NeuralNetwork/Gene/Schema.py 71.9% <0%> (+0.82%) ⬆️

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 4ccdace...93fe2fe. Read the comment docs.

@BioGeek

BioGeek commented Oct 27, 2017 •

Copy link
Copy Markdown
Contributor Author

Note: The AppVeyor tests pass, but the file where I added an extra test, test_Entrez_online.py, is skipped because internet is not available.

And apologies for pushing from the master branch. Next time I'll make a proper branch.

Comment thread Bio/_py3k/__init__.py
"""Treat a binary (bytes) handle like a text (unicode) handle."""
wrapped = io.TextIOWrapper(io.BufferedReader(handle))
try:
encoding = handle.headers.get_content_charset()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would add a comment here that you are checking the HTML headers which would be present if this was a network handle. Without context I find this is hard to understand.

@peterjc

peterjc commented Oct 27, 2017

Copy link
Copy Markdown
Member

This looks good - the test coverage has dropped ever so slightly because you've added code which does not get tested on TravisCI/AppVeyor where we deliberately do not run the online tests.

See preceeding commits from pull request #1429 to
address #1402 where on non-UTF8 locale machines
under Python 3 (typically Windows machines), we
can run into problems with characters in data
returned from the NCBI (or elsewhere) using an
incompatible encoding.
@peterjc

peterjc commented Oct 27, 2017

Copy link
Copy Markdown
Member

Looks good in local testing on the mac, here with the old code your new test fails in a non-UTF8 locale like C (ASCII only):

$ LANG=C python3 test_Entrez_online.py
test_ecitmatch (test_Entrez_online.EntrezOnlineCase)
Test Entrez.ecitmatch to search for a citation ... ok
test_efetch_biosystems_xml (test_Entrez_online.EntrezOnlineCase)
Test Entrez parser with XML from biosystems ... ok
test_efetch_gds_utf8 (test_Entrez_online.EntrezOnlineCase)
Test correct handling of encodings in Entrez.efetch ... ERROR
test_efetch_taxonomy_xml (test_Entrez_online.EntrezOnlineCase)
Test Entrez using a integer id - like a taxon id ... ok
test_egquery (test_Entrez_online.EntrezOnlineCase)
Test Entrez.egquery which searches in all Entrez databases for a single text query ... ok
test_elink (test_Entrez_online.EntrezOnlineCase)
Test Entrez.elink with multiple ids, both comma separated and as list ... ok
test_epost (test_Entrez_online.EntrezOnlineCase)
Test Entrez.epost with multiple ids, both comma separated and as list ... ok
test_espell (test_Entrez_online.EntrezOnlineCase)
Test misspellings with Entrez.espell ... ok
test_medline_from_url (test_Entrez_online.EntrezOnlineCase)
Test Entrez into Medline.read from URL ... ok
test_parse_from_url (test_Entrez_online.EntrezOnlineCase)
Test Entrez.parse from URL ... ok
test_read_from_url (test_Entrez_online.EntrezOnlineCase)
Test Entrez.read from URL ... ok
test_seqio_from_url (test_Entrez_online.EntrezOnlineCase)
Test Entrez into SeqIO.read from URL ... ok
test_webenv_search (test_Entrez_online.EntrezOnlineCase)
Test Entrez.search from link webenv history ... ok
Entrez (Bio)
Doctest: Bio.Entrez ... ok
ecitmatch (Bio.Entrez)
Doctest: Bio.Entrez.ecitmatch ... ok
efetch (Bio.Entrez)
Doctest: Bio.Entrez.efetch ... ok
egquery (Bio.Entrez)
Doctest: Bio.Entrez.egquery ... ok
einfo (Bio.Entrez)
Doctest: Bio.Entrez.einfo ... ok
elink (Bio.Entrez)
Doctest: Bio.Entrez.elink ... ok
esearch (Bio.Entrez)
Doctest: Bio.Entrez.esearch ... ok
espell (Bio.Entrez)
Doctest: Bio.Entrez.espell ... ok
esummary (Bio.Entrez)
Doctest: Bio.Entrez.esummary ... ok

======================================================================
ERROR: test_efetch_gds_utf8 (test_Entrez_online.EntrezOnlineCase)
Test correct handling of encodings in Entrez.efetch
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/pc40583/repositories/biopython/Tests/test_Entrez_online.py", line 221, in test_efetch_gds_utf8
    result = handle.read()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 342: ordinal not in range(128)

----------------------------------------------------------------------
Ran 22 tests in 18.583s

FAILED (errors=1)

Then updating to your fix, the new test passes :)

I wonder if for this test method we should explicitly temporarily change the locale to C?

@peterjc

peterjc commented Oct 27, 2017

Copy link
Copy Markdown
Member

I did wondering if a better fix would be to add an optional encoding argument to _binary_to_string_handle, but this private function is currently only used for network handles (in Bio.Entrez, Bio.ExPASy, Bio.KEGG and Bio.TogoWS), so as written seems fine. We might perhaps rename this function to indicate it is primarily for network (urllib) handles?

@BioGeek

BioGeek commented Oct 27, 2017

Copy link
Copy Markdown
Contributor Author

I have also thought about temporarily changing the locale inside the test to make more explicit what we are testing, but I wasn't sure of a proper way to do this.

Changing the name of _binary_to_string_handle is fine for me.

@peterjc
peterjc merged commit 1a32c50 into biopython:master Oct 27, 2017
@peterjc

peterjc commented Oct 27, 2017

Copy link
Copy Markdown
Member

Merged, thank you.

If you can find a good what to cleanly change the locale for this one test, that would be worth adding as a new pull request.

MarkusPiotrowski pushed a commit to MarkusPiotrowski/biopython that referenced this pull request Oct 31, 2017
* If the handle has a headers attribute, then use it's content charset as encoding. Otherwise fall back to the default behaviour.

* Add test for correct handling of encodings in Entrez.efetch.

* Also add some missing docstrings in other tests, and close handles everywhere.

This is a squashed commit from from pull request biopython#1429 to address biopython#1402 where on non-UTF8 locale machines under Python 3 (typically Windows machines), we can run into problems with characters in data returned from the NCBI (or elsewhere) using an incompatible encoding.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants