Skip to content

Commit 956eb3c

Browse files
committed
v2.6.0: use requests for URLs, and some internal cleanup. (TODO: eliminate more dead code from utils.py)
1 parent 58bbad6 commit 956eb3c

4 files changed

Lines changed: 28 additions & 48 deletions

File tree

‎language_tool_python/language_tag.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@ def __lt__(self, other_tag):
2121
def __str__(self):
2222
return self.normalized_tag
2323

24+
def __repr__(self):
25+
return f'<LanguageTag "{str(self)}">'
26+
2427
def _normalize(self, tag):
2528
if not tag:
2629
raise ValueError('empty language tag')

‎language_tool_python/server.py‎

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,25 @@
1+
from typing import Dict
2+
13
import atexit
24
import http.client
35
import json
6+
import os
47
import re
8+
import requests
59
import socket
610
import threading
711
import urllib.parse
812
from weakref import WeakValueDictionary
13+
14+
from .backports import subprocess
915
from .download_lt import download_lt
1016
from .language_tag import LanguageTag
1117
from .match import Match
12-
from .utils import *
18+
from .utils import (
19+
correct,
20+
parse_url, get_locale_language, get_language_tool_directory, get_server_cmd,
21+
FAILSAFE_LANGUAGE, startupinfo,
22+
LanguageToolError, ServerError, JavaError, PathError)
1323

1424

1525
DEBUG_MODE = False
@@ -106,12 +116,12 @@ def _spell_checking_categories(self):
106116
def check(self, text: str) -> [Match]:
107117
"""Match text against enabled rules."""
108118
url = urllib.parse.urljoin(self._url, 'check')
109-
response = self._query_server(url, self._encode(text))
119+
response = self._query_server(url, self._create_params(text))
110120
matches = response['matches']
111121
return [Match(match) for match in matches]
112122

113-
def _encode(self, text):
114-
params = {'language': self.language, 'text': text.encode('utf-8')}
123+
def _create_params(self, text: str) -> Dict[str, str]:
124+
params = {'language': str(self.language), 'text': text}
115125
if self.motherTongue is not None:
116126
params['motherTongue'] = self.motherTongue
117127
if self.disabled_rules:
@@ -124,7 +134,8 @@ def _encode(self, text):
124134
params['disabledCategories'] = ','.join(self.disabled_categories)
125135
if self.enabled_categories:
126136
params['enabledCategories'] = ','.join(self.enabled_categories)
127-
return urllib.parse.urlencode(params).encode()
137+
# return urllib.parse.urlencode(params).encode()
138+
return params
128139

129140
def correct(self, text: str) -> str:
130141
"""Automatically apply suggestions to the text."""
@@ -187,18 +198,18 @@ def _update_remote_server_config(self, url):
187198
self._url = url
188199
self._remote = True
189200

190-
def _query_server(self, url, data=None, num_tries=2):
201+
def _query_server(self, url, params=None, num_tries=2):
191202
if DEBUG_MODE:
192-
print('_query_server url:', url, 'data:', data)
203+
print('_query_server url:', url, 'params:', params)
193204
for n in range(num_tries):
194205
try:
195-
with urlopen(url, data, self._TIMEOUT) as f:
196-
raw_data = f.read().decode('utf-8')
206+
with requests.get(url, params=params, timeout=self._TIMEOUT) as response:
197207
try:
198-
return json.loads(raw_data)
208+
return response.json()
199209
except json.decoder.JSONDecodeError as e:
200-
print('URL {url} and data {data} returned invalid JSON response:')
201-
print(raw_data)
210+
print(f'URL {url} and params {params} returned invalid JSON response:')
211+
print(response)
212+
print(response.content)
202213
raise e
203214
except (IOError, http.client.HTTPException) as e:
204215
if self._remote is False:

‎language_tool_python/utils.py‎

Lines changed: 1 addition & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020
FAILSAFE_LANGUAGE = 'en'
2121

2222
# https://mail.python.org/pipermail/python-dev/2011-July/112551.html
23-
USE_URLOPEN_RESOURCE_WARNING_FIX = (3, 1) < sys.version_info < (3, 4)
2423

2524
if os.name == 'nt':
2625
startupinfo = subprocess.STARTUPINFO()
@@ -129,37 +128,4 @@ def get_jar_info():
129128

130129
def get_locale_language():
131130
"""Get the language code for the current locale setting."""
132-
return locale.getlocale()[0] or locale.getdefaultlocale()[0]
133-
134-
135-
if USE_URLOPEN_RESOURCE_WARNING_FIX:
136-
class ClosingHTTPResponse(http.client.HTTPResponse):
137-
138-
def __init__(self, sock, *args, **kwargs):
139-
super().__init__(sock, *args, **kwargs)
140-
self._socket_close = sock.close
141-
142-
def close(self):
143-
super().close()
144-
self._socket_close()
145-
146-
class ClosingHTTPConnection(http.client.HTTPConnection):
147-
response_class = ClosingHTTPResponse
148-
149-
class ClosingHTTPHandler(urllib.request.HTTPHandler):
150-
151-
def http_open(self, req):
152-
return self.do_open(ClosingHTTPConnection, req)
153-
154-
urlopen = urllib.request.build_opener(ClosingHTTPHandler).open
155-
156-
else:
157-
try:
158-
urllib.response.addinfourl.__exit__
159-
except AttributeError:
160-
from contextlib import closing
161-
162-
def urlopen(*args, **kwargs):
163-
return closing(urllib.request.urlopen(*args, **kwargs))
164-
else:
165-
urlopen = urllib.request.urlopen
131+
return locale.getlocale()[0] or locale.getdefaultlocale()[0]

‎setup.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
setup(
99
name='language_tool_python',
10-
version='2.5.5',
10+
version='2.6.0',
1111
description='Checks grammar using LanguageTool.',
1212
long_description_content_type='text/markdown',
1313
long_description=long_description,

0 commit comments

Comments
 (0)