Skip to content

Commit 1322bff

Browse files
committed
Better Unicode behavior under Python 3.
1 parent 4abc91f commit 1322bff

File tree

2 files changed

+10
-10
lines changed

2 files changed

+10
-10
lines changed

pysolr.py

+9-9
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ def force_bytes(value):
116116
"""
117117
if IS_PY3:
118118
if isinstance(value, str):
119-
value = value.encode('utf-8')
119+
value = value.encode('utf-8', 'backslashreplace')
120120
else:
121121
if isinstance(value, unicode):
122122
value = value.encode('utf-8')
@@ -245,6 +245,9 @@ def _send_request(self, method, path='', body=None, headers=None, files=None):
245245
method = method.lower()
246246
log_body = body
247247

248+
if headers is None:
249+
headers = {}
250+
248251
if log_body is None:
249252
log_body = ''
250253
elif not isinstance(log_body, str):
@@ -260,20 +263,17 @@ def _send_request(self, method, path='', body=None, headers=None, files=None):
260263
raise SolrError("Unable to send HTTP method '{0}.".format(method))
261264

262265
try:
263-
# Bytes all the way down.
264-
# Except the ``url``. Requests on Py3 *really* wants that to be a
265-
# string, not bytes.
266+
# Everything except the body can be Unicode. The body must be
267+
# encoded to bytes to work properly on Py3.
266268
bytes_body = body
267-
bytes_headers = {}
268269

269270
if bytes_body is not None:
270271
bytes_body = force_bytes(body)
271272

272-
if headers is not None:
273-
for k, v in headers.items():
274-
bytes_headers[force_bytes(k)] = force_bytes(v)
273+
if not 'content-type' in [key.lower() for key in headers.keys()]:
274+
headers['Content-type'] = 'application/xml; charset=UTF-8'
275275

276-
resp = requests_method(url, data=bytes_body, headers=bytes_headers, files=files,
276+
resp = requests_method(url, data=bytes_body, headers=headers, files=files,
277277
timeout=self.timeout)
278278
except requests.exceptions.Timeout as err:
279279
error_message = "Connection to server '%s' timed out: %s"

tests/client.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@ def test__send_request(self):
177177
self.assertTrue('"numFound":3' in resp_body)
178178

179179
# Test a lowercase method & a body.
180-
xml_body = '<add><doc><field name="id">doc_12</field><field name="title">Whee!</field></doc></add>'
180+
xml_body = '<add><doc><field name="id">doc_12</field><field name="title">Whee!</field></doc></add>'
181181
resp_body = self.solr._send_request('POST', 'update/?commit=true', body=xml_body, headers={
182182
'Content-type': 'text/xml; charset=utf-8',
183183
})

0 commit comments

Comments
 (0)