Ошибка UnicodeEncodeError: кодек ‘latin-1’ не может закодировать символ ‘u201c’ в позиции 2740: порядковый номер не входит в диапазон (256)

#xml #python-3.x #rest #encode #python-unicode

#xml #python-3.x #остальное #кодировать #python-unicode

Вопрос:

Я получаю ошибку UnicodeEncodeError: кодек ‘latin-1’ не может закодировать символ ‘ u201c’ в позиции 2740: порядковый номер не находится в диапазоне (256) при попытке создать REST POST со следующим кодом:

 import requests, sys, base64, collections, json, urllib3, re
from getpass import getpass
from requests.auth import HTTPBasicAuth
from xml.etree import ElementTree

# disable TLS warnings
urllib3.disable_warnings()

print ("nPlease enter your 1DC username:")
user = input()
print ("n")
password = getpass("Please enter your 1DC password:")
print ("n")

xml = """<?xml version="1.0" encoding="utf-8"?>
<ticket>
  <id>#####</id>
  <subject>Test Firewall Request For API</subject>
  <requester>###</requester>
</ticket>"""

header={'Authorization':'HTTPBasicAuth(user, password)','Content- 
Type':'application/xml'}

response=requests.post('https://server_ip/securechangeworkflow/api/securechange/tickets/', data=xml, headers=header, verify=False)
print (response.text.encode("utf-8"))


Traceback (most recent call last):
  File "api_tufin_7.py", line 313, in <module>
response=requests.post('https://server_ip/securechangeworkflow/api/securechange/tickets/', data=xml, headers=header, verify=False)

File "C:Program FilesPython35libsite-packagesrequestsapi.py", line 116, in post
return request('post', url, data=data, json=json, **kwargs)
File "C:Program FilesPython35libsite-packagesrequestsapi.py", line 60, in request
return session.request(method=method, url=url, **kwargs)
File "C:Program FilesPython35libsite-packagesrequestssessions.py", line 533, in request
resp = self.send(prep, **send_kwargs)
File "C:Program FilesPython35libsite-packagesrequestssessions.py", line 646, in send
r = adapter.send(request, **kwargs)
File "C:Program FilesPython35libsite-packagesrequestsadapters.py", line 449, in send
timeout=timeout
File "C:Program FilesPython35libsite-packagesurllib3connectionpool.py", line 600, in urlopen
chunked=chunked)
File "C:Program FilesPython35libsite-packagesurllib3connectionpool.py", line 354, in _make_request
conn.request(method, url, **httplib_request_kw)
File "C:Program FilesPython35libhttpclient.py", line 1083, in request
self._send_request(method, url, body, headers)
File "C:Program FilesPython35libhttpclient.py", line 1127, in _send_request
body = body.encode('iso-8859-1')
UnicodeEncodeError: 'latin-1' codec can't encode character 'u201c' in position 2740: ordinal not in range(256)
  

Я не уверен, что может быть причиной этой ошибки.

Комментарии:

1. использовать data=xml.encode('UTF-8')