|
29 | 29 | import urllib.request |
30 | 30 | import warnings |
31 | 31 | from collections import namedtuple |
32 | | -from contextlib import closing |
33 | 32 | from functools import total_ordering |
34 | 33 | from weakref import WeakValueDictionary |
35 | 34 | try: |
|
49 | 48 | FAILSAFE_LANGUAGE = "en" |
50 | 49 | LANGUAGE_RE = re.compile(r"^([a-z]{2,3})(?:[_-]([a-z]{2}))?$", re.I) |
51 | 50 |
|
| 51 | +# http://mail.python.org/pipermail/python-dev/2011-July/112551.html |
| 52 | +USE_URLOPEN_RESOURCE_WARNING_FIX = (3, 1) < sys.version_info < (3, 4) |
52 | 53 |
|
53 | 54 | if os.name == "nt": |
54 | 55 | startupinfo = subprocess.STARTUPINFO() |
@@ -217,7 +218,7 @@ def _start_server(cls): |
217 | 218 | params = {"language": FAILSAFE_LANGUAGE, "text": ""} |
218 | 219 | data = urllib.parse.urlencode(params).encode() |
219 | 220 | try: |
220 | | - with closing(urllib.request.urlopen(cls.url, data, 15)) as f: |
| 221 | + with urlopen(cls.url, data, 15) as f: |
221 | 222 | tree = ElementTree.parse(f) |
222 | 223 | except (IOError, http.client.HTTPException) as e: |
223 | 224 | raise ServerError("{}: {}".format(cls.url, e)) |
@@ -280,9 +281,7 @@ def _get_languages(cls): |
280 | 281 | def _get_root(cls, url, data=None, num_tries=2): |
281 | 282 | for n in range(num_tries): |
282 | 283 | try: |
283 | | - with closing( |
284 | | - urllib.request.urlopen(url, data, cls.TIMEOUT) |
285 | | - ) as f: |
| 284 | + with urlopen(url, data, cls.TIMEOUT) as f: |
286 | 285 | return ElementTree.parse(f).getroot() |
287 | 286 | except IOError as e: |
288 | 287 | if n + 1 < num_tries: |
@@ -498,3 +497,34 @@ def terminate_server(): |
498 | 497 | """ |
499 | 498 | if LanguageTool._server_is_alive(): |
500 | 499 | LanguageTool._terminate_server() |
| 500 | + |
| 501 | + |
| 502 | +if USE_URLOPEN_RESOURCE_WARNING_FIX: |
| 503 | + class ClosingHTTPResponse(http.client.HTTPResponse): |
| 504 | + def __init__(self, sock, *args, **kwargs): |
| 505 | + super().__init__(sock, *args, **kwargs) |
| 506 | + self.sock = sock |
| 507 | + |
| 508 | + def __exit__(self, exc_type, exc_value, traceback): |
| 509 | + self.sock.close() |
| 510 | + return super().__exit__(exc_type, exc_value, traceback) |
| 511 | + |
| 512 | + class ClosingHTTPConnection(http.client.HTTPConnection): |
| 513 | + response_class = ClosingHTTPResponse |
| 514 | + |
| 515 | + class ClosingHTTPHandler(urllib.request.HTTPHandler): |
| 516 | + def http_open(self, req): |
| 517 | + return self.do_open(ClosingHTTPConnection, req) |
| 518 | + |
| 519 | + urlopen = urllib.request.build_opener(ClosingHTTPHandler).open |
| 520 | + |
| 521 | +else: |
| 522 | + try: |
| 523 | + urllib.response.addinfourl.__exit__ |
| 524 | + except AttributeError: |
| 525 | + from contextlib import closing |
| 526 | + |
| 527 | + def urlopen(*args, **kwargs): |
| 528 | + return closing(urllib.request.urlopen(*args, **kwargs)) |
| 529 | + else: |
| 530 | + urlopen = urllib.request.urlopen |
0 commit comments