当我从Unicode字符文件中读取并尝试通过API为发生的异常创建Github问题时发生异常:
Traceback (most recent call last):
File "./item.py", line 320, in <module>
auto_issue(opt.hashToCrack, e, e.message)
File "/home/baal/bin/python/settings.py", line 480, in auto_issue
_failure(issue, hashed_string, error)
File "/home/baal/bin/python/github/create_issue.py", line 109, in _failure
urllib2.urlopen(req).read()
File "/usr/lib/python2.7/urllib2.py", line 154, in urlopen
return opener.open(url, data, timeout)
File "/usr/lib/python2.7/urllib2.py", line 435, in open
response = meth(req, response)
File "/usr/lib/python2.7/urllib2.py", line 548, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python2.7/urllib2.py", line 473, in error
return self._call_chain(*args)
File "/usr/lib/python2.7/urllib2.py", line 407, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 556, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 422: Unprocessable Entity
我做了一些研究并得出结论,当异常信息中有Unicode字符时会发生这种情况。我如何创建Github问题看起来像这样:
def _failure(issue, hashed_string, error):
def __create_issue_ext():
retval = []
for _ in range(5):
retval.append(random.choice(string.ascii_letters))
return ''.join(retval)
issue_title = "Unhandled Exception {}({})".format(issue, __create_issue_ext())
issue_data = {
"title": issue_title,
"body": open("{}/lib/github/issue_template".format(os.getcwd())).read().format(
type(error).__name__, (error.args, error.message), platform.platform(),
hashed_string, sys.argv
)
}
req = urllib2.Request(
url="https://api.github.com/repos/<name>/<project>/issues", data=json.dumps(issue_data),
headers={"Authorization": "token {}".format(__handle(__get_encoded_string()))})
urllib2.urlopen(req).read()
lib.settings.LOGGER.info(
"Your issue has been created with the title '{}'.".format(
issue_title
)
)
现在这样可行,只要Exception字符串中没有Unicode字符即可。所以我的问题是,有没有办法可以将Unicode转换为JSON格式,或者在将Unicode字符添加到JSON格式之前删除Unicode字符的异常字符串?