From 78e262140f3128cc1e24770e9ec568e9b10a925a Mon Sep 17 00:00:00 2001 From: ines Date: Tue, 1 Aug 2017 01:11:35 +0200 Subject: [PATCH] Add workaround for displaCy server on Python 2/3 (resolves #1227) Make sure status and headers are bytes on Python 2 and strings on Python 3 --- spacy/compat.py | 8 ++++++++ spacy/displacy/__init__.py | 5 ++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/spacy/compat.py b/spacy/compat.py index c2ab27d7e..4ef24cd8b 100644 --- a/spacy/compat.py +++ b/spacy/compat.py @@ -61,6 +61,14 @@ elif is_python3: json_dumps = lambda data: ujson.dumps(data, indent=2) path2str = lambda path: str(path) + +def b_to_str(b_str): + if is_python2: + return b_str + # important: if no encoding is set, string becomes "b'...'" + return str(b_str, encoding='utf8') + + def getattr_(obj, name, *default): if is_python3 and isinstance(name, bytes): name = name.decode('utf8') diff --git a/spacy/displacy/__init__.py b/spacy/displacy/__init__.py index 8468720cd..7c479f94c 100644 --- a/spacy/displacy/__init__.py +++ b/spacy/displacy/__init__.py @@ -3,6 +3,7 @@ from __future__ import unicode_literals from .render import DependencyRenderer, EntityRenderer from ..tokens import Doc +from ..compat import b_to_str from ..util import prints, is_in_jupyter @@ -65,7 +66,9 @@ def serve(docs, style='dep', page=True, minify=False, options={}, manual=False, def app(environ, start_response): - start_response('200 OK', [('Content-type', 'text/html; charset=utf-8')]) + # headers and status need to be bytes in Python 2, see #1227 + headers = [(b_to_str(b'Content-type'), b_to_str(b'text/html; charset=utf-8'))] + start_response(b_to_str(b'200 OK'), headers) res = _html['parsed'].encode(encoding='utf-8') return [res]