gpt4 book ai didi

python - 兼容性问题(python 2 与 python 3)

转载 作者:行者123 更新时间:2023-11-30 22:28:54 25 4
gpt4 key购买 nike

我有一个程序可以通过 API 自动创建 Github 问题。它可以在 Python 2.7 中运行,但是当我使用 Python 3 运行它时,出现以下错误:

Traceback (most recent call last):
File "/home/baal/bin/python/zeus-scanner/var/auto_issue/github.py", line 92, in request_issue_creation
urllib2.urlopen(req, timeout=10).read()
File "/usr/lib/python3.5/urllib/request.py", line 163, in urlopen
return opener.open(url, data, timeout)
File "/usr/lib/python3.5/urllib/request.py", line 464, in open
req = meth(req)
File "/usr/lib/python3.5/urllib/request.py", line 1183, in do_request_
raise TypeError(msg)
TypeError: POST data should be bytes or an iterable of bytes. It cannot be of type str.

我有以下方法可以创建 github 问题(在 python 2 中成功,在 python 3 中失败):

def request_issue_creation():
logger.info(set_color(
"Zeus got an unexpected error and will automatically create an issue for this error, please wait..."
))

def __extract_stacktrace(file_data):
logger.info(set_color(
"extracting traceback from log file..."
))
retval, buff_mode, _buffer = [], False, ""
with open(file_data, "r+") as log:
for line in log:
if "Traceback" in line:
buff_mode = True
if line and len(line) < 5:
buff_mode = False
retval.append(_buffer)
_buffer = ""
if buff_mode:
if len(line) > 400:
line = line[:400] + "...\n"
_buffer += line
return "".join(retval)

logger.info(set_color(
"getting authorization..."
))

encoded = __get_encoded_string()
n = get_decode_num(encoded)
token = decode(n, encoded)

current_log_file = get_latest_log_file(CURRENT_LOG_FILE_PATH)
stacktrace = __extract_stacktrace(current_log_file)
issue_title = stacktrace.split("\n")[-2]

issue_data = {
"title": issue_title,
"body": "Error info:\n```{}````\n\n"
"Running details:\n`{}`\n\n"
"Commands used:\n`{}`\n\n"
"Log file info:\n```{}```".format(
str(stacktrace),
str(platform.platform()),
" ".join(sys.argv),
open(current_log_file).read()
),
}

try:
req = urllib2.Request(
url="https://api.github.com/repos/<API-REPO>/issues", data=json.dumps(issue_data),
headers={"Authorization": "token {}".format(token)}
)
urllib2.urlopen(req, timeout=10).read()
logger.info(set_color(
"issue has been created successfully with the following name '{}'...".format(issue_title)
))
except Exception as e:
logger.exception(set_color(
"failed to auto create the issue, got exception '{}', "
"you may manually create an issue...".format(e), level=50
))

我在网上读到将字符串编码为 utf-8 可以解决问题,但我不确定这是否可能?任何帮助将不胜感激,谢谢。

最佳答案

您需要对 JSON 负载进行编码:

data = json.dumps(issue_data)
if sys.version_info > (3,): # Python 3
data = data.encode('utf8')

req = urllib2.Request(
url="https://api.github.com/repos/<API-REPO>/issues", data=data,
headers={"Authorization": "token {}".format(token),
"Content-Type": "application/json; charset=utf-8"}
)

我添加了一个带有 charset 参数的 Content-Type header ,用于与服务器通信所使用的编解码器。这并不总是需要的,JSON 的默认编解码器是 UTF-8。如果您不指定 header ,则会提供(错误的)默认值;这是否重要取决于服务器。

关于python - 兼容性问题(python 2 与 python 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46503322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com